_id
int64
0
49
text
stringlengths
71
4.19k
0
Which is better for a beginner, UDK or Unity? I am just getting into game development and I would like to know which engine would be best to learn first. In terms of my current skills, I know a good deal of javascript, but not much beyond that. This is all a learning experience for me (I am an extremely fast learner). I am using HTML5 canvas right now as that's mostly what I was hinting at when i said javascript. I probably should have made it a bit more clear.
0
(Unity) Optimised networking solution for many moving objects I've currently undertaking quite an ambitious project. In short, it's a real time multiplayer strategy game which has bacteria mechanics. Essentially, I have two remote players in the environment, and they can spawn bacteria like units which attack each other and multiply, duplicating themselves until a resource limit is hit. This often results in around 200 game objects being rendered to the screen, each with their own state and movement. This sounds bad, but the local gameplay against a bot is actually very good, and I've managed to make it quite performant. However, the issue arises when I try to network this game. I have already attempted to follow this guide to implement this feature http www.paladinstudios.com 2013 07 10 how to create an online multiplayer game with unity This produces quite a slow, displeasing game experience even with the best latency. This is likely caused by having to transmit movement data for hundreds of units. The question I am posing How can I optimize the networking and synchronization of many moving units between two clients? I've already thought of one way to do this. After spawning a unit, they will only travel in one direction until they hit something perhaps I can synchronize only when units are spawned and when they interact with another object? Would this have much benefit? What's the ideal way to implement this? Thanks in advance for responses!
0
Why only few parts of the 2D sprite change their colour when I apply sprite color in Unity? I'm making a stickman 2D game where I have different sprites for the player. But when I try to change the Sprite Renderer Color, it only changes few pixels of the sprite and the rest stays black as in the original sprite. What am I missing?
0
When serializing a class, can its fields take their defaults from the Unity editor? Can I have a custom serialized class whereby I set a value in the editor and that value persists into runtime, as happens with serialized monobehaviour fields? Currently it sets itself to 0 or a default hard coded from within the class. I noticed that using a struct actually works but using a struct breaks the events used in my actual use case (included below). Example code public class Class1 MonoBehaviour this variable can be set in the editor and persist into run time SerializeField private float testVar1 this variable can not SerializeField private Class2 class2 private void Start() class2 new Class2() Serializable public class Class2 SerializeField private float testVar2 My use case Serializable public class EditorFloat SerializeField public float value public EventProperty lt float gt eventProperty public EditorFloat(EventProperty lt float gt eventProperty) this.eventProperty eventProperty Object.FindObjectOfType lt CentralParams gt ().OnUiChange Update this.eventProperty.OnChanged UpdateEditor public void Update() eventProperty.Value value public void UpdateEditor(float valueFromEventProperty) value valueFromEventProperty Thanks!
0
How to reset a gameobject to it's prefab condition? I have a GameObject with a ragdoll in it. Gameobject comes from a prefab which is pooled. So whenever the enemy is killed it's disabled then enabled when spawn. Problem is that the ragdoll settings and it's condition cannot be reset by enabling. i.e. enemy stays dead even though respawned. Is there a way to easily reset a GameObject to prefab state? Solution online is to keep all the transforms and re apply them by code. Is this the only way?
0
Disable free look camera movement when touch detected on mobile joystick I'm using free joystick pack form asset store and in scene have two cameras (first person and third person). Switching cameras with toggle. Game starts with first person camera. Moving with fixed joystick and rotating camera with swiping on right side of screen. Everything is ok for this step. For third person camera I'm using cinemachine free look camera. Cinemachine camera is reacting to joystick touch inputs. I need to disable camera movement when interacting with joystick. Tested on Android device Cinemachine settings Third Person movement script void Update() if (Application.platform RuntimePlatform.Android Application.platform RuntimePlatform.IPhonePlayer) x joystick.Horizontal z joystick.Vertical else x Input.GetAxis( quot Horizontal quot ) z Input.GetAxis( quot Vertical quot ) Vector3 direction new Vector3(x, 0, z).normalized if (direction.magnitude gt 0.1f) float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg camTps.transform.eulerAngles.y float angle Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime) transform.rotation Quaternion.Euler(0f, angle, 0f) Vector3 moveDirection Quaternion.Euler(0f, targetAngle, 0f) Vector3.forward characterController.Move(moveDirection.normalized speedTps Time.deltaTime) Any ideas and suggestions is appreciated
0
Random environment runtime generation in Unity I need a tip for a project basically I need to randomly generate an environment (a map) for a game. As generating a full map completely procedural is impossible for me, I thought to create a static map (I made one ice based, one rock based, one desert based etc) with some static elements in it like a "spawn area", a map border. Next, I made some "piece of map" smaller that the actual size of the border (like the border is 1000x1000 and this piece are max 200x200). Each piece has the same style of the border (e.g. I made few icy pieces with a spawn of polar bear and few desert pieces with a spawn of scorpions). Now I'm stuck I can't randomly spawn all the little squares inside a border amp I can't randomly spawn them inside and make them match one with an other. Incidentally, this is a 3D project.
0
How to create a trail like this in Unity? I want to create a trail like this game... When the plane flies it creates this trail... It's possible because the game itself was made in Unity... But I can't find any options to do so... Any help would be much appreciated...
0
Webgl page heap size increasing in each page load then crash I am getting aw snap or sometime not enough memory problem when I reload my webgl page. I have a webgl project which is empty (just a camera light), developed in unity3d. I am reloading it, and profile its memory. As you can see that its load 1.2MB in the first load than 1281 MB in second then 1574 then 2160 and then get crash. I am amazed that why it is happening? Another source of memory related problems is the IndexedDB filesystem used by Unity. Any time you cache an asset bundle or use any filesystem related methods, they are stored in a virtual filesystem backed by IndexedDB. What you might not realize is that this virtual filesystem is loaded into and persisted in memory as soon as your Unity application starts. This means that if you are using the default Unity caching mechanism for Asset Bundles, you are adding the size of all of those bundles to the memory requirements for your game, even if they are not being loaded. but the problem is I didn't load anything from this build yet. Even when I try to refresh my empty project several time in chrome I get this error For Mozilla, there is an error log which states failed to asynchronously prepare wasm out of memory
0
Draw rectangles on Cube and remove I have 3d object as Wall ( Cube with texture and width and height large ) with some texture and attached c ( Unity 5.3.2 ) script to that wall. I want to programmatically draw rectangles on that Wall with green semitransparent color and after 5 seconds remove them. I am new to Unity and found OnGui but it is not drawing in 3d space but in front of screen. How to achieve this to draw and remove rectangles on Wall ?
0
Integrate Stripe with Unity I'm trying to install the Stripe API Library through NuGet Manager in Visual Studio but it installs it inside packages folder of the Project (I.E. before Project's Assets folder) doing this I cannot use the library Using UnityEngine Using Stripe Doesn't recognise this Then I Moved those installed files from packages to Assets folder Uninstalled Stripe from NuGet (as I could now access them in my script by using Stripe) Now these are the main errors that I'm getting PrecompiledAssemblyException Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included for the current platform. Only one assembly with the same name is allowed per platform. Assembly path 0 Assembly 'Assets Temp lib netstandard2.0 Stripe.net.dll' will not be loaded due to errors Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform? Assembly 'Assets Temp lib netstandard1.2 Stripe.net.dll' will not be loaded due to errors Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform?
0
Unity C moving objects and Debug.Log show multiple messages only once (easy but stuck) I have the following scenario a sphere is moving towards an object it can see (a cube). The cube is moving randomly through the landscape. The sphere will keep following it. I have a script that will check IF the cube is Within Sight. If it is, it will move towards it and it will keep following it. What I want I want a Debug.Log message to show when When the sphere is moving towards a (new) target. it must say "Searching..." When the sphere has found the cube, I want it to say "Found the cube." When the cube is found, I want it to continue searching for new cubes. So it must say once more "Searching..." Problem It keeps showing these messages nonstop. I found a solution with a false bool in an IF statement. But, I don't know how to combine 2 messages. Code using UnityEngine using BehaviorDesigner.Runtime using BehaviorDesigner.Runtime.Tasks public class MoveTowards Action public float speed 0 public SharedTransform target private bool pietje private bool jaap void PrintMessage (string message) Debug.Log(message) void Start() pietje false public override TaskStatus OnUpdate() if (Vector3.SqrMagnitude (transform.position target.Value.position) lt 0.1f amp amp !pietje) PrintMessage ("Found the cube.") pietje true return TaskStatus.Success transform.position Vector3.MoveTowards (transform.position, target.Value.position, speed Time.deltaTime) transform.LookAt (target.Value.position) return TaskStatus.Running I just don't know how to fix the last part where it says "Searching..." I don't know how to implement it with an IF statement (doesn't work somehow) or how to create the IF statement (when I use this, it doesn't work if (TaskStatus.Running 1 amp amp !pietje) Anyone that can help me? That would be awesome! Have been trying to fix this for some hours now....
0
Unity 2D sprite animation keep in sync after setting inactive I am creating a 2D sprite based game and the tile map contains many animated background tiles (such as water). The map contains many areas that can be transitioned between in a Zelda style (camera scrolls to new area). After scrolling, I set the previous area to inactive. Setting the area to inactive pauses the animations (which is what I want), but when I reenter a previous area the animations start from where they left off. Therefore, any animated tiles adjacent to each other between screens are out of sync and cause an obvious seam. I would like for all the background tile animations to run on the same time value even after they've been paused. The animations use an Animator Controller attached to each animated tile GameObject with an Animation that changes the sprite from an atlas. Another idea I had would be to have a separate class modify my texture atlas (maybe using setpixel) to update the tiles to their next frame of animation (since I want all tile animations to be in sync and run at the same speed), but I'm not sure how updating the texture will affect performance. I would like to hear people's ideas for any solutions to this problem.
0
Why does Unity editor freeze up if left unfocused for a while? If Unity editor loses focus for too long (such as because I'm tabbed out into my browser or Blender), then I find that it needs about 15 30 seconds until I can interact with it again when it gets focus again. It seems like it is paused. Is this a bug or my fault?
0
Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences? The first script the manager is attached to new empty gameobject I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager using System.Collections using System.Collections.Generic using UnityEngine public class DialogueManager MonoBehaviour public DialogueTrigger dialoguetrigger private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () dialoguetrigger.TriggerDialogue() DisplayNextSentence() public void StartDialogue(Dialogue dialogue) Debug.Log("Starting conversation with " dialogue.name) sentences.Clear() foreach(string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() Debug.Log(sentence) void EndDialogue() Debug.Log("End of conversation.") Next the DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue() FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Last the Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue public string name TextArea(3, 10) public string sentences In the editor I filled the all 3 TextAreas each one with a sentence. Hello world Hi everyone I have woke up When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log.
0
How can shader code duplication be reduced in Unity? In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code. On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again. How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?
0
Why my Edit Collider in Unity2D has no point to adjust size? Why when I clicked to Edit Collider of Box Collider 2D component, is not showing points for me resize the collide box?
0
Emission for Mobile Shaders? I need to use Emission texture to my model, but I can't find any emission parameters in mobile shaders. I searched this on google, but there's nothing helpful to me. How do I add emission for mobile shaders, without writing own shader code? (I'm keep studying shader but still not good at)
0
How can teams collaborate on Unity 3D projects? With a friend of mine, we are planning to develop a small game to get the hang of game development and teamwork. But since Unity 3D barely supports version control (or at least the free version lacks of it) we have no idea how to efficiently manage teamwork. Sharing tasks in a small project is also seems like a challange for us. I would also appreciate any advice that could be useful for beginner indie developers related to teamwork. )
0
Clamp joystick rotation in Unity I'm trying to create a mobile joystick using this free package from Unity. Here is the code for rotation which seems to be working fine. I just want to clamp the rotation to 90 or 90 degress. I have tried using the mathf.clamp function but the plane(player) completes a full rotation. public Joystick joystick float rotateVertical float rotateHorizontal float minClamp 90.0f float maxClamp 90f void Update() rotateVertical Mathf.Clamp(joystick.Vertical 1f, minClamp, maxClamp) rotateHorizontal Mathf.Clamp(joystick.Horizontal 1f, minClamp, maxClamp) transform.Rotate(rotateVertical, 0, rotateHorizontal) If I change the value of minClamp to 0, then the plane doesn't rotate on the negative x axis but is still able to complete a full rotation on the positive x axis. Can someone please help me?
0
Floor is made up of tiles with their own box colliders. Pushable item gets stuck on the "seams" So I have a scene where the floor is made up of some tiled objects. All of these have the exact same height and exact same Y position. I also have a block with a rigidbody that you can push on the ground. It has a rigidbody with freeze rotation enabled for X, Y, and Z. My issue is this when pushing the block around, it sometimes gets stuck when reaching the seams of the tiled objects. I have tried giving it a friction of 0, but it still gets stuck sometimes. Is there any solution for this, other than manually creating a big collider that spans the entire floor?
0
Correctly get size from Canvas UI element on Unity Normally when anchors are on the same position, we can use .sizeDelta or .rect.width height from RectTransform, but if the anchor are stretched, both of them returns negative values Which in reality is not 5 in size at all There are already SetSizeWithCurrentAnchor but how to get other's RectTransform's absolute size?
0
Google Play Services Library not found. How can I get this? So this question is in relation to, but not the same as my previous question (How do I successfully implement Google Mobile Ads and Google Play Services into my Unity arcade game?). That is why I am making a new one. I am almost ready to publish my app now the I have ads working but in the process of implementing Unity Ads I was forced to re implement Google Play Services. I did so with an updated version of Google Play Services and now I am receiving this error Does anyone know how to fix this?
0
Why even use coroutines in Unity? I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's Update method. By using a IEnumerator coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re usability of the component using them. Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?
0
Unity Syncing Downloading overwriting files to a local folder accessed by the game when offline? I currently have a game application (PC Standalone only) made in Unity which features a multitude of buttons which all link to external webpages which open up in the user's browser window. Recently my client expressed an interest in having an offline version, where all the online content is available locally offline, as their users regularly go offsite to areas without an internet connection and the buttons are then useless. I have done a new version which has all the webpages, PDFs and videos saved off as local files and placed in a folder within the build folder, the buttons now use the following script to read the files from there instead public class URLOpener OFFLINE MonoBehaviour public void relativeURL(string url) Application.OpenURL(url) This works perfectly on a basic level. However my client has expressed an interest in being able to update the offline content without having to make a new build each time or manually go and update the folder content. So basically what I need is to be able to store all the offline files somewhere online, which can be overwritten as and when is needed. Then I need some way of syncing the game with this online location (when the user is online), to pull down the latest files into the offline folder and overwrite the files in there, so the latest offline files are included when they go offsite to an area without internet. Is this possible at all? I am more than happy to pay for a plugin or service that would provide this sort of feature. I already have a plugin for translated languages which essentially does this (https www.assetstore.unity3d.com en ! content 14884) changes to the online spreadsheet containing all the text is pulled down when the game syncs. But this is obviously a bit different to downloading actual files and placing them in a specific folder. Any help or advice would be appreciated. Many thanks in advance
0
Isometric camera movement My camera system has two objects the isometric camera itself, and an empty object it's attached to which handles both movement and rotation. When the player drags the middle mouse button, the camera (or, rather, the empty object) moves like this Vector3 diff lastFramePosition currFramePosition float xchange diff.x 5 float ychange diff.y 5 flips the direction of movement if the rotation of the object is a certain way if (transform.rotation.y 90 transform.rotation.y 180) ychange 1 if (transform.rotation.y 270 transform.rotation.y 180) xchange 1 Vector3 pos transform.position moves the camera and restrains it within the limits of the map (core.mapx and core.mapy) transform.position new Vector3(Mathf.Clamp(xchange pos.x, 0, core.mapx), 3, Mathf.Clamp(ychange pos.z, 0, core.mapy)) It turns out, though, that since it moves the empty object along the X and Y axes, dragging up down or left right moves it along those axes instead of actually moving the camera view up down and left right. The best way I can describe it is like those old isometric games that do the exact same thing. Is there any way I can get it to move like this?
0
How to approach debugging of java.lang.NullPointerException in android build of unity app? We are getting an obscure java.lang.NullPointerException when building a Unity app for android. There's not much information here that I can trace back to our code. Does anyone have advice about how to approach debug this? All I have to go on at the moment are logCat logs Uncaught exception thrown by finalizer java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java 891) at bitter.jnibridge.JNIBridge.disableInterfaceProxy(Unknown Source 0) at bitter.jnibridge.JNIBridge.delete(Native Method) at bitter.jnibridge.JNIBridge a.finalize(Unknown Source 15) at java.lang.Daemons FinalizerDaemon.doFinalize(Daemons.java 250) at java.lang.Daemons FinalizerDaemon.runInternal(Daemons.java 237) at java.lang.Daemons Daemon.run(Daemons.java 103) at java.lang.Thread.run(Thread.java 764) (Unity version 2018.1.0b10)
0
Make platform's visibility distinct from background I have a 2d infinite runner type game which background is changing its colors constantly. Meanwhile the color of the platforms stays the same. This way the platforms at some point(when their color is the same as the background's) become "invisible" for the player. How can I creatively, shortly and conviniently avoid this problem with unity? P.S. I've tried adding glossy material to it but it didn't work.
0
How to limit and direct player's view in VR? We are making a VR game where the player will look at the world through the eyes of his character who sometimes moves on his own, so the player is only observer. The character will rotate his body on his own and we need to change the orientation of player's camera to look where the character looks. For example, the girl takes his hand and leads her way. It would be very unrealistic if the player's head will be turned 180 from his body and he will walk backwards. It'll allow us to avoid exhausting head rotations. Is it a good idea to guide his view by force by limiting camera euler angles relative to the direction of the body?
0
In 2D, how can I improve character rotation using raycasts when dealing with sharp convex edges? Edit After making some edits to my polygon collider (based on Alex F's suggestion), I can indeed confirm that sharp, convex corners are causing the buggy rotation. For now I've decided to only rotate my character if its moving, so standing on a corner when velocity.x 0 won't cause my collider to rotate rapidly. However, this seems like a band aid fix, and I'm still wondering if there's a better way to handle these edges. Resuming movement after idling on a corner still causes some buggy behavior, and I'm concerned that this will compound once my rotations become more complicated or frequent Original question I'm quite inexperienced with quaternions and rotating, so I'm not entirely sure if this issue has to do with my code, the collisions shown in this question, or my game design. What I'm trying to achieve is "smooth" rotation of my character's collider based on the normal of the current surface. I've been creating a custom raycast controller in 2D from the ground up, and already know how to find all kinds of information from rays, such as the current angle of a sloped surface. My controller is coming along quite nicely, and rotation is one of the last things I'd like to tackle. It should be able to handle sloped box colliders, but also irregular ground shapes that require something like a polygon collider. I've been somewhat successful, having learned that I shouldn't set my character's z rotation directly, but instead update my entire transform.rotation with a method like Quaternion.Lerp. This has worked generally well, but I'm running into issues on irregular ground, and on corners. Notice the smooth transition from flat to sloped surfaces, but that my collider rotates rapidly when the raycast hits a corner Movement is still somewhat smooth on irregular terrain, but there is a noticeable shakiness at times. Sometimes my character's collider rotates rapidly as well (end of gif) I suspect that the shakiness on the irregular terrain is just my collider getting "caught" on the many edges that the polygon collider creates. I just don't know if this is happening because I could be doing something differently in my code, or if I need to edit the polygon collider, or is caused by something else entirely. Perhaps raycasting isn't the best way to achieve my desired behavior. SerializeField private float speed 5 SerializeField private float gravity 20 SerializeField private LayerMask collisionMask private BoxCollider2D boxCollider private Vector2 velocity private Vector2 groundNormal private void Awake() boxCollider GetComponent lt BoxCollider2D gt () private void Update() float playerInput Input.GetAxisRaw("Horizontal") velocity.x playerInput speed velocity.y gravity Time.deltaTime MoveCharacter(velocity Time.deltaTime) private void MoveCharacter(Vector2 velocity) Rotate the character Quaternion targetRotation Quaternion.FromToRotation(Vector2.up, groundNormal) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, 0.5f) groundNormal Vector2.zero CollideBelow(ref velocity) transform.Translate(velocity) private void CollideBelow(ref Vector2 deltaMovement) float rayLength 1 Vector2 rayOrigin transform.position RaycastHit2D hit Physics2D.Raycast(rayOrigin, transform.up, rayLength, collisionMask) Debug.DrawRay(rayOrigin, transform.up rayLength, Color.red) if (hit) velocity.y 0 deltaMovement.y (hit.distance boxCollider.size.y 0.5f) groundNormal hit.normal
0
How to render a large number of colored dots in 3d space? I would like to create a game similar to Scanner Sombre. The player is in a dark environment and can't see their surrounding unless they use a scanner. That scanner sends out rays which mark little dots on all surfaces, creating 3D map of environment. I tried to just paint visible dots on transparent textures, but that does not work because the dots are supposed to always face the player. I considered to instantiate a new game object for every single dot. But as the game progress, the player will see billions of these dots at once, and that would likely be terrible in terms of performance. Can someone suggest a possible technique to do this?
0
Export baked lightmaps from Unity to Monogame I'm trying to bake lightmaps in Unity, export as textures and apply the textures in Monogame. Is this the right path to go? If so, how it should be done? Thank you.
0
Unity2D Collision Issue I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching. How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders?
0
How to make a door stay open if the player is inside the trigger zone? I've been struggling with this for all day long, I want to make a door to stay open when the player is inside the trigger zone, but I cannot make it happen... Here is what I did A basic animations and animator (Open, Close, Idle Default) Default transitions between states (with and without "Exit Time") A basic script to check if the player is inside the trigger using System.Collections using System.Collections.Generic using UnityEngine public class DoorScript MonoBehaviour Animator animator bool doorOpen Use this for initialization void Start () doorOpen false animator GetComponent lt Animator gt () Update is called once per frame void Update () void OnTriggerEnter(Collider other) if (other.tag "Player") doorOpen true DoorController("isOpen") void OnTriggerExit(Collider other) if (other.tag "Player") doorOpen false DoorController("isClosed") void DoorController(string trigger) animator.SetTrigger(trigger) And my result is the same, the animation of the door repeats itself even when the player is in the trigger zone, I tumbled upon some other resources (here... here... here... here I tried to copy what this person did, but is the same... here... and here) about doors and triggers, and I still don't know how I am wrong or what am I doing wrong, I tried everything in those links The door goes through all animations regardless the script, and the parameters, when I move my player inside the trigger zone loops between open and close animations no matter what Could some one help me with this? Thanks in advance EDIT Here are some screenshots of my animator and updated code, for this update I followed this tutorial, just a little difference, I'm using a FPS Controller from the Unity standard assets Updated code using System.Collections using System.Collections.Generic using UnityEngine public class DoorScript MonoBehaviour Animator animator bool doorOpen Use this for initialization void Start () doorOpen false animator GetComponent lt Animator gt () Update is called once per frame void Update () void OnTriggerEnter(Collider other) if (other.gameObject.tag "Player") doorOpen true DoorController("isOpen") void OnTriggerExit(Collider other) These lines were modified if (doorOpen) doorOpen false DoorController("isClosed") void DoorController(string trigger) animator.SetTrigger(trigger)
0
Angle object only in the X axis I'm trying to code a turret to angle towards a target, where I have one part of the turret only rotating on the left right, and I want to animate another part to only angle up down. I've got the left right (RotateTowardsTarget) working, but I can't get the up down (AngleTowardsTarget) to work, it seems to also rotate the object as well as angle it. turretXRotation is a child of turretYRotation. These objects form the top of a gun turret, so the base will rotate, and the gun barrel will angle towards the target lt summary gt Orient the turret weapon towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void OrientWeaponsTowards(Vector3 lookPosition) RotateTowardsTarget(lookPosition) AngleTowardsTarget(lookPosition) lt summary gt Rotate towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void RotateTowardsTarget(Vector3 lookPosition) Determine which direction to rotate towards Vector3 targetDirection lookPosition transform.position The step size is equal to speed times frame time. float singleStep weaponRotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards( turretYRotation.transform.forward, targetDirection, singleStep, 0.0f ) Draw a ray pointing at our target in Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3) newDirection.y 0 Calculate a rotation a step closer to the target and applies rotation to this object turretYRotation.transform.rotation Quaternion.LookRotation(newDirection) lt summary gt Angle towards the target. lt summary gt lt param name "lookPosition" gt lt param gt private void AngleTowardsTarget(Vector3 lookPosition) Determine which direction to rotate towards Vector3 targetDirection lookPosition turretXRotation.transform.position The step size is equal to speed times frame time. float singleStep weaponRotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards( turretXRotation.transform.forward, targetDirection, singleStep, 0.0f ) Draw a ray pointing at our target in Debug.DrawRay(turretXRotation.transform.position, newDirection, Color.red, 3) Calculate a rotation a step closer to the target and applies rotation to this object turretXRotation.transform.rotation Quaternion.LookRotation(newDirection) Does anyone know how I can just make the turretXRotation only change it's X value to aim towards the target? I've tried similar stuff to the rotating, by zeroing out some of the x y z coords, but I can't seem to crack it.
0
What is the difference between HDRP materials and normal materials I want to understand these materials I am always confused of using HDRP materials that which one is used for low texture which one is for high texture, for glass, for particles and many other.
0
Collision, triggering, and range detection in an RTS. What are the optimal solutions for unit spatial awareness? I've finally ran into the problem of multiple triggers and collisions within my 2D RTS. Up till now I've been using unities sphere colliders as a way of simulating spatial awareness. To trigger when objects have entered and exited a specific area around a unit or building so that they can be appropriately targeted. This became a performance problem when I started having hundreds of colldiers overlapping each other. Since the units are aware of projectiles as well as other units buildings, this becomes very expensive very fast. I've found that I can only manage to have a couple hundred projectiles and about 100 colliders within close proximity of each other before the game slows to a crawl just from PhysX. (hundreds of projectiles entering and exiting 100 collliders all the time) I did some research and found spatial partitioning mentioned all over the place. Is this a solution to the problem I am currently presented with? Are there other solutions for objects to have spatial awareness of potentially hundreds of other objects at a time without bringing my CPU to it's knees?
0
How to calculate the reachable space of the end effector in an IK chain? I have an array of points in a 2d worldspace and I want to calculate which points are reachable by the end effector of a limb controlled with a CCDIK chain (with rotation limits applied). It's a limb with 2 hinges (upper arm amp lower arm) The upper amp lower arm have a fixed length The 2 hinges have fixed rotation limits This needs to be recalculated every update (continuously) as the limb is attached to a moving body I work in Unity using C Crude Illustration of the problem My idea sofar is to create a polygon collider along the outer edges of the reachable space, and then look if the points are within the bounds of that collider. But I have no idea if this is the smartest solution, or if so, how to achieve this. How could I solve this issue?
0
Scaling of a bone is working while rotation is not Unity3d I'm using Unity3d and I'm trying to rotate the left leg bone of an avatar but it is not working although scaling is working well. This is the code used for scaling and is working perfect r.localScale new Vector3( 0.1f , 0.1f , 0.1f) and these are my attempts to is the code of rotation but not working r.eulerAngles new Vector3(10, 10, 10) r.rotation transform.rotation r.rotation where r is the transform of the left leg. EDIT This is my file. So this doesn't work when I'm using the Update function, like nothing happens to the avatar. If I used LateUpdate function, I can see the rotation made but then flickers back to the old position, I wonder how to apply the rotation to all the remaining frames as well. If anyone could please advise
0
In Unity, how do I make a 3D flight arc preview? I'm stuck on how to make a preview trajectory for a projectile appear when holding a button. The trajectory should start at a certain position on the scene and end wherever the player points their mouse. On mouse click, a projectile should be launched along that trajectory with the clicked position as its target. How can I do this?
0
How to program (architecturally organize) a set of customizable changes to a game? The floor of my game (tower defense) is composed by a set of cubes. I wish to change these on some of the waves. I have a list of the changes that need to be made on each wave in a floorController class. However, in order to decide which floor cubes should appear or disappear on each round, I had to assign each cube a bool for each wave (if this is set to true the floor changes in that wave). However this process is tedious and not ease to change and customize in order to experiment with the level. From an architectural programming perspective how can I better structure this system?
0
How can I make custom character face editor In my game In an optimal way? In many games there Is section as customize character that you can make your own character.I always love to know how can I make something like It. Even old game have this feature? but how ? For Implementing It I need accurate separation for communating between values and facial parts size. So first I made multiple height map based on facial parts for modifying by vertex shader and work correctly but this method Isn't optimal.can I Implement It just by one texture? then I tried by using colorful mapping texture for detecting facial parts, but I have problem for getting color values from mapping texture In my shader code. mapping texture My problem Is that my vertex shader Isn't match with my mapping texture.for example If I change NoseLength other parts will changes.how can I tell to vertex shader which part is nose,forehead,lip,cheek,... In my colorful mapping. Here Is my Shader Code Shader "Custom Extrude" Properties MainTex ("Base (RGB)", 2D) "white" ModTex ("Vertex Modify", 2D) "white" NoseLength ("NoseLength ", Range( 0.05,0.01)) 1.0 LipSize ("LipSize ", Range( 0.05,0.01)) 1.0 CheekBones ("CheekBones ", Range( 0.05,0.01)) 1.0 ForeHead ("ForeHead ", Range( 0.05,0.01)) 1.0 EyeSize("EyeSize", Range( 0.05,0.01)) 1.0 SubShader Tags "RenderType" "Opaque" "Queue" "Transparent" Cull off CGPROGRAM pragma surface surf Lambert vertex vert pragma target 3.0 sampler2D MainTex sampler2D ModTex uniform fixed NoseLength uniform fixed LipSize uniform fixed CheekBones uniform fixed ForeHead uniform fixed EyeSize struct Input float2 uv MainTex void vert(inout appdata full v) float4 lipSize tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).g Green float4 nose tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).b Blue float4 eye tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).r Red float2 cheek tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).rg Yellow float2 forehead tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).rb Purple v.vertex.y LipSize lipSize v.vertex.y NoseLength nose v.vertex.y EyeSize eye v.vertex.y CheekBones cheek v.vertex.y ForeHead forehead void surf (Input IN, inout SurfaceOutput o) half4 c tex2D ( MainTex, IN.uv MainTex) o.Albedo c.rgb o.Alpha c.a ENDCG FallBack "Diffuse"
0
New clients don't see objects spawned before they connect I'm making a game with UNet where the server must create some objects when he connects to the game, and all clients play with these objects that the server has created. A server connects to the game In his start method he calls a function CmdbuildEverything to spawn some objects to the game. A local player connects to the game. The local player should be able to see the objects that the server player has created. The code public class GameScript NetworkBehaviour void Start() if(base.isServer) CmdbuildEverything() Command void CmdbuildEverything() GameObject ob1 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 0, 1), Quaternion.identity) GameObject ob2 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 1, 0), Quaternion.identity) GameObject ob3 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(1, 0, 0), Quaternion.identity) NetworkServer.Spawn(ob1) NetworkServer.Spawn(ob2) NetworkServer.Spawn(ob3) The problem is that the objects are created only on the server player and don't appear on the clients payers. How can I solve that?
0
Varibles Initialized in Awake are null in other script's Start I have a component gameState Attached to one gameobject called GameState public class gameState MonoBehaviour public Context stateMachine private void Awake() PlayerGameobject p GameObject.Find("Player").GetComponent lt PlayerGameobject gt () stateMachine new Context(new Playing(), p) On another gameObject I have this component public class PlayerGameobject MonoBehaviour void Start() gameState GameObject.Find("GameState").GetComponent lt gameState gt () When I try to use gameState within PlayerGameobject's Update method I find that stateMachine is null. if (gameState.stateMachine.CurrentState "Playing") null why is statemachine null? I initialized it in awake which should run before start. gameState is not null and other public variables assigned in Editor are not null.
0
Create 3D line instead of a thin line in Unity in runtime with mouse drag I know how to use line renderer to drag and drop to create line in runtime, but the line appears to be thin when looking from the end of the line, I want to create a real line that has a thickness(think of it as a tube or pipe shape), no mater where the look direction is, they should has a thinkness. How would you achieve this effect, I've got two ideas, 1.Create a rectangle shape, then extrude this shape to create mesh during runtime, but the manipulation of mesh during runtime is too complicated for me. or 2.Create prefabs, and spawn new prefabs and connect them along the cursor routing to make them looked as they were a continous line. Would you suggest me of some new ideas or existing package to achieve this effect, or is the first option is the way to go? What I want to do is to make a shader editor like appearence in 3D space, what I need to create is the edges, and the edges should look 3D instead of 2D line.
0
OnCollisionEnter2D just flat out not running for certain objects I am working with the Unity3D Engine in 2D mode. Currently I am trying to make a circle collider bounce off of a composite collider for the walls of my game. The only issue is that for some reason the OnCollisionEnter2D function does not seem to even trigger when the circle collider hits the walls. I have used the log to determine this. I am curious as to why it has this behviour, since it does end up triggering when the player contacts the circle collider? Here is the important parts of the script public class sword MonoBehaviour public Rigidbody2D rb public CircleCollider2D coll public float speed public Vector2 trajectory public GameObject Player Use this for initialization void Start () speed 0.0f anim Player.GetComponent lt Animator gt () private void OnCollisionEnter2D(Collision2D collision) Debug.Log("collided") if (collision.gameObject.tag "player") transform.position new Vector2( 1000, 1000) Player.GetComponent lt movement gt ().equipped true if (collision.gameObject.tag "solid") ContactPoint2D otherObject collision.contacts 0 Vector2 hit otherObject.point Vector2 normal otherObject.normal trajectory Vector2.Reflect(trajectory, normal) private void FixedUpdate() constantly calculating new velocity rb.velocity speed trajectory speed speed 0.93f drag if (speed lt 0.0001f) speed 0.0f if (speed gt 1) Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, true) else Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, false) More Details My speed variable is set from a separate script, in case you are wondering. Everything is on the layer 0.. The Rigidbody for player is dynamic, for the ball it is kinematic, and for the walls it is static. Also here is an image of what the game screen would look like, I've labelled the walls and the circle collider (used for a sword). Thank you.
0
Change alpha value of object if it's closer to the camera than the player Ok, so I'm a complete idiot when it comes to shader programming, and while I suspect someone with some experience here may find this easy, I'm at a bit of a loss. I'd like to create a shader that would be applied to walls, and if the wall was closer to the camera than the player is, the wall would gain alpha transparency (probably 10 20 visible). I had tried some things with a camera that pans, zooms, and moves overhead as needed to not occlude the player, but it's sloppy and just doesn't feel very nice. I had used an x ray shader, that showed an outline of the player through the wall, and while it was "cool", it also didn't quite feel right. The camera and player will always be a fixed distance and angle apart (well, at least at a given resolution). Is there some way to use the draw buffer or otherwise calculate world space position to determine when alpha should be applied? Any help is very much appreciated. Thanks! EDIT I was looking and found a lot of solutions like this one https forum.unity3d.com threads global shader to apply transparency on objects depending how far is the camera.188632 But I'd rather have it contained entirely in the shader. Preferably something I could build into a copy of the Standard (Specular Setup) shader in Unity that copy being applied only to wall objects. EDIT 2 I understand that this could be done with two separate materials, using code to swap them with Raycasting (though it seems that that would only work specifically for objects directly between the camera and the player rather than objects closer to the camera than the player). But I'm growing more uncertain that the shader can be told anything about the position of the player as an object.
0
How to give and remove authority of an object between multiple clients (Or how to let the client controller push a rigidbody) I'm doing a cooperation FPS game in which players can push big rigidbody cubes with their rigidbody characters (the one from the standard assets). The problem is that the player hosting the game has authority on these cubes positions and so when the client tries to push them, he really struggles and the result is 100 disappointing. So i'm searching a way to pass authority from the server to client and vice versa when the cube is touched by a player. I'm using Unity 2018.2 Have a nice day.
0
Unity Bool doesn't change to false anymore I got into a Unity Tutorial and halfway through I face this weird problem. I used this code so that my player may attack if he pressed a leftShift. When the player attacks, the animation starts playing in a loop he never stops attacking and debugging show that attack is never false after the first "leftShift" Input. I removed the loops from the animator etc. but that doesn't seem to be the problem because "attack" never get's to false anyways. I tried different approaches. If I set "attack false" immediately after attacking, he doesn't attack at all. Sorry for asking such a beginner question but I can't seem to find my error. using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour private Rigidbody2D myRigidbody SerializeField private float movementSpeed private bool facingRight true private Animator myAnimator private bool attack false Start is called before the first frame update void Start() myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void Update() HandleInput() Debug.Log(attack) Update is called once per frame void FixedUpdate() float horizontal Input.GetAxis("Horizontal") HandleMovement(horizontal) Flip(horizontal) HandleAttacks() ResetValues() private void HandleMovement(float horizontal) if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) myRigidbody.velocity new Vector2(horizontal movementSpeed, myRigidbody.velocity.y) myAnimator.SetFloat("speed", Mathf.Abs(horizontal)) private void HandleAttacks() if (attack) myAnimator.SetTrigger("attack") private void HandleInput() if (Input.GetKeyDown(KeyCode.LeftShift)) attack true attack false private void Flip(float horizontal) if(horizontal gt 0 amp amp !facingRight horizontal lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale private void ResetValues() attack false
0
Help for structuring classes I am creating a platformer game with some card base fighting. I was thinking about how should I structure my classes? There are 2 types of cards i.e. Continuous effect and 1 time effect. Also, they can be divide into 3 other categories i.e. Environment cards, enemy cards and player cards. Please help me to get started with structuring it. For more details, I want structure to be reusable as well as organized. Enemies and player both can interact with these cards and at some points. Thank you
0
In app purchases Restore unlocked items on new device I am building a mobile game for Android iOS with support for in app purchases. Our game also supports unlock codes (aka promo codes). A user can enter an unlock code in our app to unlock one or more IAP items for free. We want to ensure, that if a user changes his device, we is able to restore all IAP items and unlocked items. As the promo code feature provided on app stores is either quite limited in functionality or not available at all, we've decided to build our own backend to manage unlock codes. If a user enters an unlock code, we register this in our backend. So, when a user re installs the app, we need to talk to two systems to get the full list of purchased unlocked items Talk to app stores to fetch list of purchased items Talk to our own backend to fetch list of unlocked items To make sure that the user gets his unlocked items even after an app reinstall on a different device, we need to have an identifier which is not based on the device but rather on a user account. Unity does not provide access to Apple ID Google ID, so my question is, how to accomplish this in a good way? At the moment, the only possible solution I see is this Users must register with us (e.g. email and password). We store the list of unlocked items in our own backend. In case of an app reinstall on a new device, the user must login to our backend and unlocked items become available again. Are there any better solutions to this?
0
Unity3D 5.5b C WebGL open email client Win32 exception error I want to send an email in a WebGL build using C . My code is as below try Uri myUri new Uri("mailto anemailaddress example.com? Subject Hello 20again amp body TEST") System.Diagnostics.Process.Start(myUri.AbsoluteUri) catch (Win32Exception e) Debug.LogError(e.Message) catch (Exception e) Debug.LogError(e.Message) to open an email client. But I get the following error as well as a Win32Exception Success error (Filename Users builduser buildslave unity build artifacts generated WebGL runtime DebugBindings.gen.cpp Line 51) a9b4b6fe b629 4efc bb29 821d1f0fcea2 9085 3 Not implemented icall Process ShellExecuteEx internalUnityLoader.js 3541 3 Success (Filename Users builduser buildslave unity build artifacts generated WebGL runtime DebugBindings.gen.cpp Line 51)
0
Memory managing fully removing an item from a dictionary of GameObjects Unity When you have a dictionary that looks like Dictionary lt string,GameObject gt dictionaryOfGameObjects, for removing an item from the dictionary, do you have to Destroy(gameObject) and dictionaryOfGameObject.Remove(stringid) as well?
0
How to make a delayed mouse input? I have a car game and the idea is that the player is drunk. I want to have a delayed input from the mouse, where you move the mouse side to side to turn. How can I setup a constant delay between the input the user gives and the turn amount of the car? Right now I have this h Mathf.Lerp(h, (((Input.mousePosition.x Screen.width) 2) 1), Time.deltaTime 2) What happens is the turn is delayed, but is very slow, in other words, if I move the mouse very fast, the car turns very slowly, but if I crank up the multiplier for Time.deltaTime, the car turns faster, but delay effect is minimized. How else could I do this?
0
In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)
0
How to split 2 teams for a FPS death match game in Unity? I'm making a playable one level only FPS death match game in Unity. I'm in the part where the AIs now can find and shoot their own target and keep looping to find targets until nothing left. Every AIs and including player were tagged with tag "Target" for the AIs to randomly find their target. (I already excluded self finding). Now I want to split them in 2 teams. And here is the thing that I keep wondering. Should I use 2 tags for 2 teams (like team red, team blue for ex) then make and attach 2 scripts separately for each AI in the team (the logic in the script will be like "team red" will find game object with tag "team blue" and vice versa). Is that how it works? Is there more efficient way or should I say, "smarter" way to work around this problem? Here is the script if you need to know more about what I am trying to say https github.com Bezari0us FPS AI Behaviour
0
Unity stop play only background music I have a music sound clip simply drag n dropped to my hierarchy. I also have other sound effects in my game. I want to pause play background music on button press but only music, not all sound effects. How can I reach this music GameObject in C code?
0
Why is the character not walking right when creating new animator controller for the character? I created a new controller called it SoldierController and dragged it to the character Controller under Animator component in the Inspector. Also unchecked Apply Root Motion Then attached a new script to the third person character called the script Soldier. Then I set the Animator controller and I added two new States to it Walk and Idle. HumanoidIdle and HumanoidWalk. Then I did that the default start state will be Idle. Set StateMachine Default State. Then I did a Transition from Walk to Idle. This way when I press on "W" it starts walking a bit. Then it keep moving the character but without the walking animation. If I delete this transition and make transition from the Idle to Walk then when I press on "W" it will walk but then if I leave "W" key it's idling. Then after 2 3 seconds the character will walk on place I mean it will animate walking without moving and I'm not pressing anything it's starting automatic when idling. The character had another animator controller but I created a new one and using only the new one. The script using System.Collections using System.Collections.Generic using UnityEngine public class Soldier MonoBehaviour private bool isWalking false private Animator anim Use this for initialization void Start () anim GetComponent lt Animator gt () Update is called once per frame void Update () var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f transform.Rotate(0, x, 0) if (Input.GetKey("w")) if (! isWalking) isWalking true anim.Play("Walk") var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Translate(0, 0, z) Only move when "w" is pressed. else if ( isWalking) anim.Play("Idle") isWalking false
0
How does Unity know that you make more than one hundred thousand dollars on the Personal plan? How do they check if you make more than 100k? That is really puzzling me.
0
Collisions on editor mode, or saving changes in play mode through script I have a prefab that has a collider. This collider serves as an obstacle. The thing is that I want to remove this collider from all objects inside another collider defining the map limits. This way, objects inside the game area will keep their collider, but those outside the play area get their collider removed, and serve just as decoration. I can't use the OnTriggerEnter2D as physics are disabled in editor mode. But applying the changes in play mode is no good neither, as changes are not saved. How can I create an script that checks if a collider is inside another collide in editor mode, so I can remove it if it does? Or is there any way to create a script that runs on play mode and use the OnTriggerEnter to delete the collider I want, then save the changes for the editor? Using bouding boxes is no good, as the collider delimiting the play area is an irregular polygon collider. Any ideas?
0
Helicopter controller, spherical world with faux gravity I followed this tutorial to create a planet with faux gravity that attracts objects. Further I'm trying to create a helicopter like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with AddForce to Rigidbody and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with AddForce is not applied, but still the control feels very awkward. What would be the best way to compensate the faux gravity to move the helicopter? Edit I only need it to move in XY plane (so only up down left right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now. Player controller (assigned to the helicopter) public class PlayerController MonoBehaviour public float moveSpeed 15 private Rigidbody rb private Vector3 moveDir private float h private float v void Awake() rb GetComponent lt Rigidbody gt () if(!rb) throw new Exception("Game Object must have Rigidbody!") void Update () GetControls() moveDir new Vector3(h, v, 0).normalized void GetControls() h Input.GetAxis("Horizontal") v Input.GetAxis("Vertical") void FixedUpdate() rb.MovePosition(rb.position transform.TransformDirection(moveDir) moveSpeed Time.deltaTime) Faux Gravity Attractor (assigned to the planet) public class FauxGravityAttractor MonoBehaviour public float gravity 10 public void Attract(Transform body) Vector3 gravityUp (body.position transform.position).normalized Vector3 bodyUp body.up Rigidbody bodyRb body.GetComponent lt Rigidbody gt () bodyRb.AddForce(gravityUp gravity) Quaternion targetRotation Quaternion.FromToRotation(bodyUp, gravityUp) body.rotation body.rotation Quaternion.Slerp(body.rotation, targetRotation, 50 Time.deltaTime) Faux Gravity Body (assigned to the helicopter) public class FauxGravityBody MonoBehaviour SerializeField float gravity 10 public FauxGravityAttractor attractor private Transform myTransform void Start () Rigidbody rb GetComponent lt Rigidbody gt () rb.constraints RigidbodyConstraints.FreezeRotation rb.useGravity false myTransform transform void Update () attractor.Attract(myTransform)
0
Unity gameobject design approach for item drops In a game like Minecraft, the player could have any of several hundred types of items in their inventory. Players can drop those items into the world, but obviously how they're rendered in the world differs from how they're rendered in the inventory. I'm trying to understand how to design for this scenario using Unity's GameObject concept. Individually, it seems like the expectation is that I would have one GameObject (with at least a SpriteRenderer) for every unique item that can appear in world. I would have one GameObject (with at least an Image component) for every unique item that can appear in inventories. With so many, I also need to come up with some sort of directory so that I can associate bulk prefab objects for use in game. Is this accurate? I feel like that's a lot of overhead. Would I be able to create one GameObject with both a SpriteRenderer and an Image and maybe toggle between then based on whether its in world or an inventory? I had also considered using one generic GameObject and replacing the sprite image based on the item needed, but that feels like it's misusing what GameObjects are meant for. It also likely subverts the benefit of pooling them, etc. Is there another approach I'm missing?
0
Prevent Unity from crashing your computer? Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC. What happened I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late. Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example?
0
Issue with interpolation on a burn shader (lerp and smoothstep) I'm trying to create a simple burn shader. See here for more info on the method I'm using. However, I don't get why replacing the smoothstep with a lerp results in completely different results. Am I missing something from my knowledge of maths? As far as I know they should return similar values given the same parameters. clips materials, using an image as guidance. use clouds or random noise as the slice guide for best results. Shader "Custom Dissolving" Properties MainTex ("Texture (RGB)", 2D) "white" BorderTex ("Border Texture (RGBA)", 2D) "white" EdgeColor ("Edge Color", Color) (1,0,0) EdgeSize ("Edge Size", float) 0.1 SliceGuide ("Slice Guide (RGB)", 2D) "white" SliceAmount ("Slice Amount", Range(0.0, 1)) 0.2 MaterialToggle UseClipInstruction ("Use Clip Instruction", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" Cull Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM if you're not planning on using shadows, remove "addshadow" for better performance pragma surface surf Lambert alpha addshadow struct Input float2 uv MainTex TEXCOORD0 float2 uv SliceGuide TEXCOORD1 float SliceAmount sampler2D MainTex sampler2D BorderTex sampler2D SliceGuide half SliceAmount half EdgeSize half3 EdgeColor void surf (Input IN, inout SurfaceOutput o) o.Alpha 1 Green is a good color for estimating grayscale values half fragSliceValue tex2D( SliceGuide, IN.uv SliceGuide).g ifdef UseClipInstruction clip(fragSliceValue SliceAmount) else TODO look for an alternative to this if (fragSliceValue SliceAmount lt 0) o.Alpha 0 endif half rampX smoothstep( SliceAmount, SliceAmount EdgeSize, fragSliceValue) half3 ramp tex2D( BorderTex,half2( rampX,0) ) EdgeColor.rgb o.Emission ramp (1 rampX) o.Albedo tex2D( MainTex,IN.uv MainTex) ENDCG Fallback "Diffuse" Left is the result of smoothstep (the provided code), right is what happens when I replace smooth with lerp.
0
Why does collision only work when keys are being pressed? My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1. I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world. So, I would like to know if I'm doing it right or is there another way to do it. Patrol.cs public class Patrol MonoBehaviour public Transform patrolPoints public float speed private int currentPoint private bool forward Use this for initialization void Start () transform.position patrolPoints 0 .position currentPoint 0 forward true Update is called once per frame void Update () if (transform.position patrolPoints currentPoint .position) if (currentPoint lt patrolPoints.Length 1 amp amp forward) currentPoint else currentPoint forward false if (currentPoint 0) forward true transform.position Vector3.MoveTowards (transform.position, patrolPoints currentPoint .position, speed Time.deltaTime)
0
Unity3d saving with prefabs Bad Idea? I am developing for Android.In my game data is in objects which aren't derived from MonoBehaviour.So I am using binary serializer and taking references from the gameobject.It works, but I have too many variables to save most of variables are in script attached to gameobject Gamemanager So I made a prefab of gameobject of Gamemanager and saved it using prefabutility and load it again It works but Can someone tells me whether this is right approach or not, please??
0
Unity Rotating X on camera changes result of ScreenPointToRay completely I am using ScreenPointToRay to draw a Line along my Mouse drag. My code for getting my mouse position looks like so public static RaycastHit RaycastScreenPoint(Vector2 mousePosition, LayerMask mask, Camera cam) var ray cam.ScreenPointToRay(mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit, float.PositiveInfinity, mask)) Debug.DrawRay(hit.point, Vector3.up, Color.red, 2) return hit else throw new System.Exception("Mouse raycast did not hit anything") With my perspective camera at 65, 0, 0, this works great. However, if I change the rotation of my camera to 90, 0, 0, the line is drawn outside the camera view, why is this? I want this line to be drawn the same no matter the camera rotation. My code for drawing line private void Update() if (Input.GetMouseButtonDown(1)) lr.positionCount 2 startPos PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point lr.SetPosition(0, startPos) else if (Input.GetMouseButton(1)) endPos PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point lr.SetPosition(1, endPos) else if (Input.GetMouseButtonUp(1)) endPos PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point lr.SetPosition(1, endPos) This image is with the camera rotation at 64, 0, 0. As you can see, the Line is drawn inside the camera view as intended, and follows my mouse This image is with the camera rotation at 90, 0, 0. I am dragging my mouse in the middle of the game view, and yet for some reason, the line is ending up outside the camera
0
How can I create an "afterimage" effect like this one? How can I make an effect like this? With a particle system?
0
How does Unity know that you make more than one hundred thousand dollars on the Personal plan? How do they check if you make more than 100k? That is really puzzling me.
0
How to export a terrain from Unity to Blender? I'm trying to make an environment for my scene that consists animations and other objects such as trees. Making a terrain in Unity seem to be a lot easier than in Blender, so I want to export that environment which I've made in Unity to Blender. How can I do this?
0
Unity Access to svPosition in fragment shader I am trying to access to the svPosition in my fragment program in Unity but I keep having this error. invalid input semantic 'POSITION' Legal indices are in 1,15 invalid ps 3 0 input semantic 'POSITION' Here are some information about my whole shader. struct float4 pos SV POSITION vertex o.pos mul(UNITY MATRIX MVP, v.vertex) fragment col.rgb i.pos.xyz Any idea how to access this value?
0
Can I detect collision on specific collider? I'm a beginner with Unity and I'm developing my very first 2D game. My game character needs to have an automatic right left movement but I'm struggling with the colliders on the walls (I made a tilemap object and set a collision for each wall on it). I need my character to detect the collision on the Right wall and turn to the left but I just can't find a way to name (I don't even know if you can do this) and detect a specific collider collision so I can make an if statement on the player script. How can I detect a specific collision collider and refer this on my player script? Here is the code I'm using for it (it isn't working) void OnCollisionEnter2D(Collision2D collision) if (collision.collider.gameObject.name "Right Facing Wall") runForwards false else if (collision.collider.gameObject.name "Left Facing Wall") runForwards true
0
Unity Set quad to angle of floor mesh I have a cursor object (simple quad) that I'm moving around above a floor mesh. The floor mesh has varying heights (hills and such). How can I set my quad to sit at the same angle as the mesh floor? I'm using a raycast to cast down on the position of the cursor and get the angle of the floor mesh using hit.normal, then reflect. RaycastHit hit var rayStart new Vector3(transform.position.x, transform.position.y 5f, transform.position.z) if (Physics.Raycast(rayStart, Vector3.down, out hit, 10f)) if (hit.collider.tag quot Floor quot ) Vector3 incomingVec hit.point rayStart Vector3 reflectVec Vector3.Reflect(incomingVec, hit.normal) cursorSprite.transform.eulerAngles reflectVec (I've left out the position code, that works, its just the angle code that doesnt) I've tried a bunch of variations, altering the reflectVec angle x, y and z but I can't figure out how to get it correct
0
Trigger an event only if two colliders fully cover each other Let's say I have two different objects that can go through each other. Both have a circle collider (2d) that has the exact same size and there is a good chance that the two colliders will completely overlap each other. How can I trigger an event when that happens?
0
How do I make a rainbow hue shift over time on text? What I'm trying to do is make a Text object have an animation that allows for the hue of the color to go all the way up and loop back around, so it creates a cool rainbow thing. I've looked on google for a solution but the solution I found only worked in older versions of Unity, which were used back in 2015. What I found Any help would be appreciated!
0
I imported both the rig and baked animation seperatly from Maya, but it's not working correctly I am using the animation controller to bind the "jump" animation I did onto the rig itself. I don't get any errors. The animation plays. Except it seems to only affect the root joint only. Basically the model moves but not the arms or legs. They stay static. So If i have a character jumping few feet away, the entire model rig will move in jump motion(X and Y axis), but nothing happens with legs and arms. What's going on?
0
How can I display Unity games in Flex? We have tried the following methods to upload sample Unity3D build to a desktop application in Flex HTML Loader, NavigateToURL, iFrame and resolvePath. But we only see the text content, not the 3D content. What is the solution for that? How can I host a Unity game inside Flex?
0
Changing the camera movement in unity I have a code that allows me to move the camera on the x axis. I need it to move on the y axis as well as the x. using UnityEngine using System.Collections public class orbit MonoBehaviour public float turnSpeed 4.0f public Transform player private Vector3 offset void Start () offset new Vector3(player.position.x, player.position.y 8.0f, player.position.z 7.0f) void LateUpdate() offset Quaternion.AngleAxis (Input.GetAxis("Mouse X") turnSpeed, Vector3.up) offset transform.position player.position offset transform.LookAt(player.position)
0
First object jumps on re entry of second colliding object The scenario is that I have two objects Object A and Object B. The Object A is lying on the ground and when Object B enters the collider of Object A, the Object A moves (only X and Z axis) with Object B. The movement works well with the script shown below. The issue is that most of the time, the Object A's initially position shifts by few meters whenever Object B enters its collider. I feel it is related to offset position. What should happen is that, Object A should be the same position when Object B enters the collider and move along with Object B only when Object B moves. So how do I fix this? private Vector3 offsetPosition public Transform ObjectB public bool ObjectB Collision false void Start () offsetPosition ObjectB.transform.position this.transform.position void ObjectB HasEntered() offsetPosition ObjectB.transform.position this.transform.position Update is called once per frame void LateUpdate () if (ObjectB Collision true) this.transform.position new Vector3 (ObjectB.transform.position.x, this.transform.position.y, ObjectB.transform.position.z) new Vector3 (offsetPosition.x, 0, offsetPosition.z) public void OnTriggerEnter (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB HasEntered() ObjectB Collision true public void OnTriggerExit (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB Collision false
0
How do I get objects using layer name? I am creating an FPS game in local multiplayer. One player creates the hot spot game, and the other one connects through WiFi network and plays the game. I want to find all of the player objects on the network that have a specific layer name, and store them into an array when the player spawns on the network. I've been able to add the object to the array, but I can't find the layer's objects with what I found with Google searches. LayerMask.NameToLayer("LayerName") LayerMask.LayerToName(8) This returns the name of layer and layer index. How can I get the objects using a specific layer name, and also store it in to an array?
0
Unity3D Screen Capture of particular UI elements How can I screenshot particular UI elements? In my case I need screen capture UI Panel with child objects like UI Text, UI Input and etc. Please take a look at picture. Thanks in advance
0
Should I use Async Await, instead of Coroutines, in Unity? Should I use Async amp Await in Unity? Or should I keep using Coroutines? If I should use Async amp Await, how can I do so in a manner comparable to Coroutines?
0
Unity3D Firing a projectile from orbit I am dropping bombs from a spaceship orbiting a planet. My camera is affixed to the ship. I fire bombs by instantiating a bomb at the position of the camera, which is at all times facing toward the planet, however, the bomb is not intended to move directly toward the planet center. Rather, there is a movable crosshair between the camera and the planet and I want the bomb to move from the camera in the direction of the crosshair. My bomb script looks like this public class bomb MonoBehaviour public float speed GameObject crosshair Use this for initialization void Start () crosshair GameObject.Find ( quot Crosshair quot ) transform.SetParent (null) transform.LookAt (crosshair.transform) Update is called once per frame void Update () transform.Translate (transform.forward Time.deltaTime speed) My expectation is that the bomb instantiates at the camera, disassociates from its parent (the camera), turns to face the crosshair and then moves in that direction until it hits the planet. But that's not what happens. For reasons unknown, the projectile travels due left of the camera. So I adjust my projectile to move transform.right instead of transform.forward. And this works half of the time. Here's what it looks like on the West (working) Here's what it looks like on the East (not working) The projectiles are kind of small, but trust me, they're there. As mentioned, my ship is orbiting the planet. If it is orbiting on one hemisphere (0 180), it shoots toward the planet, but if it is on the other hemisphere(0 180), it shoots directly away from the planet. I can't explain this, because the camera continuously looks toward the planet, and the crosshair is always between the two, and the bomb disassociates from them anyway.
0
Do I have to re assign localized text every time the game loads? I am trying to build a localization system for games. And I have stumbled upon a problem where in Unity you basically have to change all the text in Text components any other references like audio when loading a game every time. To better explain it if the default language is English and user decided to change language to any other. Even if you localize all the files used in the game via code, later on you will have to do it again, when user loads the game after quiting it. Because components don't persist data changed via code in run time. How do I make it so that user would be able to change the language once, and all of those references and text... would persist and didn't require re set up every time the game is loaded? Is that even possible in Unity? Or should I just localize after the game has been made. And just allow people to download different language versions. But then again, it makes it difficult for people who want to change their language.
0
How can I inspect 3D model exactness? I am neither a game designer nor a graphic designer. I am a .Net and C software developer. I have a game project and I've still been studying to learn game concepts and technolgies for a year. I've decided to create a 3D based and networked MMO game with Unity3D. I've planned to hire graphic artists to do my game assets. However, I only know what I want? In other words, I only know concept of 3D models. What I have to request from graphic artists and how can inspect their work? Do I have to determine some quality criterias or something like this? Same questions are also valid for humanoid and NPC animations. Thanks
0
How to duplicate Blender glow and reflection effects in Unity? I am trying to make my game more interesting by making a background with this NEON tunnel made of glowing lines. Since I am not a good 3D artist, I choose to hire some freelancers, and they made a model that looks great in Blender. I have all that I need...but when I import my object into Unity, it does not have any effects, any colors, any glow or any "mirror" reflection. The biggest problem is that I cannot find any other freelancer who actually knows how to fix this problem. This is how it shows up in Blender when my freelancers made it, and it looks perfect I want to have the same effects, same look, same colors, same glow in my Unity project, but I don't know how to actually import this object and reproduce that same look. This is all zip folder which contain pictures, object in blender file, same object in .fbx,.obj.mtl and in many more formats.. but seems like any of those models doesn't work in Unity because I bet Unity needs more modifications... I hope someone will help me step by step to achieve my goal.
0
Position an object at the center of the screen I need to create a grid of squares such as the grid is centered on the screen. Here is a schema I need the two green lengths to be equal, and the two red lengths to be equal. Here is the method I am using right now to try to generate this pattern (slotGrid is a 2D array, but only its size is revelant right now). void GenerateLevel(bool , slotGrid) The size of the grid, in the image above this is equal to 2 as it is a 2 2 grid Note that I assume that the grid width and height are equal int slotGridSize slotGrid.GetLength(0) The size of one of the square float slotSizePixel m Slot.transform.lossyScale.x The size of the screen float screenWidthPixel Screen.width float screenHeightPixel Screen.height Debug.Log("Screen size " screenWidthPixel " " screenHeightPixel) Position of the upper left square float firstSlotX (screenWidthPixel (slotGridSize slotSizePixel)) 2 float firstSlotY (screenHeightPixel (slotGridSize slotSizePixel)) 2 Debug.Log("First slot position " firstSlotX "," firstSlotY) Vector3 newSlotPosition new Vector3(firstSlotX, firstSlotY, 0) Generate the grid starting from upper left corner for (int i 0 i lt slotGridSize i ) for (int j 0 j lt slotGridSize j ) Instantiate(m Slot, newSlotPosition, Quaternion.identity) newSlotPosition new Vector3(newSlotPosition.x slotSizePixel, newSlotPosition.y, 0) newSlotPosition new Vector3(firstSlotX, newSlotPosition.y, 0) However, this method is placing the squares in some weird position (i.e far off the screen). I realized this is because I mix pixel size (for the screen width and height) and... Unity scale size I guess (I don't know the proper name) for the square size. How can I fix this?
0
Is it possible to make an obj with single triangle I am not good in using blender so i wanted to ask if it is possible to make an object with just one triangle and how would it look like, will the no of triangle increase if you scale it up.
0
How can I move my player on exact x and y coordinates, like on a grid? I'd like to implement movement exactly like it is done in this game. (You can see it in action on YouTube.) I need my Player to always stay in the center of X and Y similar to grid movement, but with free movement line like. Only move on x and y lines. And I need smooth changes at intersections. var x Input.getAxis("Horizontal") var y Input.getAxis("Vertical") var deltaPos Vector2.zero if (Mathf.Abs(inputY) gt Mathf.Abs(inputX)) deltaPos.Y speed inputY Time.deltaTime else deltaPos.X speed inputX Time.deltaTime transform.position deltaPos
0
How can I have cutouts in a texture? I want to be able to have a gameobject that's basically just a black box on top of everything else. Then I want to be able to place other gameobjects which are just gradients on top of that and they should "cut out" of the black texture like this How can I achieve this sort of effect? Please keep in mind that I have pretty much no experience with shaders ) Here's a video that might help explain what I'm trying to achieve https www.youtube.com watch?v L1dd4fkVSAM
0
Unity how to render to texture with VR distortion I've also asked the question here http answers.unity3d.com questions 1392099 how to set a render to texture camera to be a vr c.html (but it's currently "under moderation") So, I want to do some post processing effects in VR. I put a camera as a child of the Main Camera and set it to render to texture. Then, I take what is rendered, and display it (with my post proc shader) on a quad in front of the Main Camera (The main camera and the child camera render different layers, so I don't render the same thing twice). (Also worth noting I know that the depth will be collapsed out of the rendered to texture content this is intentional.) The problem is, in this process, the positional data (that was rendered to texture) gets misaligned. I've already fixed a problem where I have to manually set camera project.GetComponent lt Camera gt ().aspect main camera.GetComponent lt Camera gt ().aspect every frame. (Changing setting the screen size auto sets the aspect ratio of the main camera it does not automatically set the aspect ratio of the child camera. So, with just that, everything lines up great and looks fine when it isn't in VR. But, when it is in VR, it appears that maybe some distortion is happening to the main camera that isn't happening to the render to texture camera, and thus, the overlay (the post proc'd content) isn't lining up. So what can I do to emulate the VR distortion in the child camera? Are there other properties of the Main Camera that are getting auto set in VR that I can manually copy to the Main Camera? (I also noticed that aspect wasn't listed in the camera documentation https docs.unity3d.com Manual class Camera.html unless you knew to search for it explicitly, so I think it might be likely there is some other property I'm missing?)
0
Unity3d app immediately goes to background after starting up on iOS So the iOS build of my game started doing this today and I have no idea why. The only think I can think of is that I added this line Application.runInBackground true but this should not force it to go to the background on startup. Other games run just fine on the phone. It's very unlikely that the game itself is using too much resources. It does not crash it just goes into the background and when you select it from there it stays on for like a second and then goes back. Has anyone experienced this before ?
0
In Unity, Meta Files are Tracked but Behaviours Fall Off My team is working on a Unity game, and we are using a mercurial repository on BitBucket. Whenever we update, all of the behaviours 'fall off' of state machines, behaviours, etc. When searching for a solution, I discovered that this information was stored in the meta files. I had previously ignored the meta files, but the are now being tracked. However, the files still 'fall off'. I cannot find any other reason this would be happening. Any assistance you can give me would be appriciated. Let me know if you need any additional details.
0
In Unity, why do I get a "does not implement right interface" error when trying to sort my list of objects? I am trying to create a crafting panel that sorts the list of items you can make alphabetically, yet I cannot figure out why .Sort() is not working. What I have is a game object that holds a list of all the items you can make and the requirements, then in my crafting script I access the game object for the list and display the info. Everything works fine until I try to sort anything. craftDatabase is what I need to be sorted. Also, it needs to be sorted by ItemID. using UnityEngine using System.Collections using System.Collections.Generic public class CraftDatabase MonoBehaviour public List lt Blueprint gt craftDatabase new List lt Blueprint gt () System.Serializable public class Blueprint public string itemId public int itemAmount public float itemCraftTime 1f public CraftPanel.subsections subsection public CraftPanel.workstations workStation public List lt requiredItem gt requiredItems new List lt requiredItem gt () HideInInspector public string desc System.Serializable public struct requiredItem public string itemId public int itemAmount public Blueprint() When I try to throw in craftDatabase.craftDatabase.Sort() it gives me this error ArgumentException does not implement right interface How do I fix this error to use Sort()?
0
Applying a torque to a different centre of mass In Unity I have an object with a circle collider attached to it and when I apply a torque to this object's rigidbody2D, it rotates as expected. However, I have now attached a sub object to this object with a polygon (trigger) collider which I am using to detect when something is in a cone in front of the ship. There is no rigid body (2D or 3D) attached to the child object. The only rigid body on the object is the one I am applying torque to. However, when I do this, the centre of mass of the ship is moved to the centre of this collider, which produces totally the wrong effect. This happens even if I move this collider to the root node (so both it and the circle collider are attached). I either need a way of getting the rigid body to ignore the child collider allow me to set the centre of gravity, or else some other way of detecting objects inside a region.
0
Unity GameObject jumps to wrong point at start In Unity, I have this problem where the Game Object this script is attached to jumps to Z position 0 as soon as the game runs. In the Editor, I have the Game Object set as Z position 50. I want startPos to read this position ( 50) and use it when newPos is updated. Why does startPos get updated immediately to 0? using UnityEngine public class MoveOutScript MonoBehaviour public float speed 10f float startPos Vector3 newPos float changePerSecond2 public void Start() startPos transform.position.z changePerSecond speed Time.deltaTime public void Update() region Move sprite away steadily newPos.z changePerSecond newPos.z Mathf.Clamp(newPos.z, startPos, 15f) transform.localPosition newPos endregion
0
what is best iap unitypackage (Asset) for support google play amazon in unity 2019.1.9? I need a unitypackage easy and easy for In app purchasing in googleplay and amazon (for Android) Which unitypackage is best in unity 2019.1.9?
0
Should I use scenes in Unity for menus? I assume scenes are for different levels, but should I use them for menu screens or is there a specific tool for menu screens?
0
How can I make that when the first animation end the next animation will start but from the same position? I have two animations. The first animation I downloaded from the Mixamo site. The game start when the player is on his back on the ground and then slowly stand up. When the animation end the player is standing Look at the player legs Then it's starting playing the next animation idle animation Look at the player legs now when the idle animation start There is no problems with the animations. It's just when the first animation end the player legs move close to each other because the legs position in the start of the second animation is not the same position when the first animation end. I need somehow to make if it's possible that the first animation legs will end at the position of the second animation start. Now the legs are moving to each other and it looks funny. If I was showing a gameplay you will see the legs moving to each other like the player is closing his legs. This screenshot is of the Animator controller where the left New State is the first animation and the Grounded is a blend tree with the idle animation inside And this is a screenshot of the blend tree and the first top state is the idle animation The transition between the two animations looks bad funny. The player is closing his legs. Instead I wish there was a way to make the first animation to end with the legs close like in the second animation start.
0
How is the value of transform.position updated and accessed between different private methods? I followed this YouTube video but I'm still confused about how the code actually retrieves the value of transform.position. I can understand the Camera.main.ScreenToWorldPoint code is to transform the screen position to a position in the world based on the camera's view, and it then uses this to update the transform.position as in the private void OnMouseDrag method. However, I also learnt that since the method is declared as private, the quot transform.position quot cannot retrieve the value of quot transform.position quot in each bracket. So how does the value of quot transform.position quot in private void OnMouseUp, private void Awake get updated, unless I misunderstood the concept? using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class GreenBird MonoBehaviour Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude lt 0.1) timeSittingAround Time.deltaTime if (transform.position.y gt 10.00 transform.position.y lt 10.00 transform.position.x gt 10 transform.position.x lt 10) string currentSceneName SceneManager.GetActiveScene().name SceneManager.LoadScene(currentSceneName) void OnMouseDown() GetComponent lt SpriteRenderer gt ().color Color.red private void OnMouseUp() GetComponent lt SpriteRenderer gt ().color Color.white Vector2 directionToInitialPosition initialPosition transform.position GetComponent lt Rigidbody2D gt ().AddForce(directionToInitialPosition launchPower) GetComponent lt Rigidbody2D gt ().gravityScale 1 birdWasLaunched true private void OnMouseDrag() Vector3 newPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position new Vector3(newPosition.x, newPosition.y)