Exclude removed objects from list counting? I want to count the number of objects on my list. But because I remove and add, my script keep count those empty elements. update This happen when I destroy the object when it inside the collider. This object does not get out from quot OnTriggerExit2D quot . public List lt GameObject gt Sorts public List lt GameObject gt ItemsInside public int NumSorts, NumItems Update is called once per frame void Update() NumSorts Sorts.Count NumItems ItemsInside.Count it doesn't give correct number void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Sort quot )) Sorts.Add(other.transform.gameObject) if (other.transform.name ( quot GameItem quot )) ItemsInside.Add(other.transform.gameObject) void OnTriggerExit2D(Collider2D otherOut) if (otherOut.CompareTag( quot Sort quot )) Sorts.Remove(otherOut.transform.gameObject) if (otherOut.transform.name ( quot GameItem quot )) ItemsInside.Remove(otherOut.transform.gameObject)


Touch a specific area on the screen in Unity 5 I am building a Roulette game in Unity 5. I want to place bets on a Roulette table when I touch specific areas on the screen with mouse(PC) and touch(mobile). For example when i touch Number 1 on the roulette table a bet should be placed on that number. I tried using box collider iwth trigger but I think thats for only colliders. Screenshot attached


Manually creating an instance of object derived from MonoBehaviour I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour. The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock. I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class. What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?


error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression' When I build my project, which references the System.IO.Compression namespace, the build succeeds without issue inside Visual Studio. However, inside the Unity editor, I see the following error error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'. This type has been forwarded to assembly 'System.IO.Compression, Version 4.0.0.0, Culture neutral, PublicKeyToken b77a5c561934e089' Consider adding a reference to that assembly. I added a csc.rsp file inside my Assets folder, with the following line r System.IO.Compression.FileSystem.dll Unfortunately, that did not resolve the issue. Here are the properties of the System.IO.Compression DLL that I reference inside Visual Studio How can I fix this error?


How to write a custom shader in Unity 3D that lights up a specific pixel or group of pixel? I'm making a FPS game in Unity, and I want the environment to light up as the player is shooting on his environment. The map would be entirely put in darkness at the beginning, but as the player shoots the environment, it would be rendered with its "real texture". So say I have a tree. First it is entirely black or greyish, but if I shoot somewhere, I would see some green. To accomplish this, I'm using a raycast to get the impact point and so I can access any renderer of the point that the player is shooting on. I guess the next step would be to write a custom shader to light the exact pixel that is shot. Do you have any idea how I could write this shader or another way of doing this effect? Regards


IL2CPP Vector.Dot inconsistency I get inconsistent results when I run this code as standalone Windows on Mono and IL2CPP backends. var a new Vector3( 1.26998901f, 0, 0.849998474f) var b new Vector3(20.0799999f, 1, 164.580002f) var dot Vector3.Dot(a, b) var mydot (float) ((double) a.x (double) b.x (double) a.y (double) b.y (double) a.z (double) b.z) Mono or Editor IL2CPP dot 165.394135 165.394119 mydot 165.394135 165.394135 Take a look at the dot result on IL2CPP backend in the table above. My mydot implementation should be equivalent to Vector3.Dot(Vector3, Vector3) according to dotPeek in Rider. Decompiled Vector3.Dot(Vector3, Vector3) lt summary gt lt para gt Dot Product of two vectors. lt para gt lt summary gt lt param name "lhs" gt lt param gt lt param name "rhs" gt lt param gt public static float Dot(Vector3 lhs, Vector3 rhs) return (float) ((double) lhs.x (double) rhs.x (double) lhs.y (double) rhs.y (double) lhs.z (double) rhs.z) Unity version 2018.4.12f1 What causes Vector3.Dot(Vector3, Vector3) to give a different result on IL2CPP?


translation and rotating at the same time and waiting before animation? I am having difficulties here. I want to move my character with the buttons and I want the character to rotate wherever he is going. Also I want to play an animation when there is no keys pressed. I am able to do that but I want the animation to play after 10 seconds of no key being pressed, and only once. Than after a movement that resets and again after 10 seconds of no key the animation plays. (The animation works but it happens right after I stop pressing a key and continuously.) IEnumerator Test() yield return new WaitForSeconds(10.0f) void Update() if (Input.GetKey(KeyCode.W)) counter Time.deltaTime transform.Translate((Vector3.forward) moveSpeed Time.deltaTime) Debug.Log("Pressing W key") if (Input.GetKey(KeyCode.S)) counter Time.deltaTime transform.Translate((Vector3.back) moveSpeed Time.deltaTime) Debug.Log("Pressing s key") if (Input.GetKey(KeyCode.A)) counter Time.deltaTime transform.Rotate(Vector3.down rotateSpeed) Debug.Log("Pressing a key") if (Input.GetKey(KeyCode.D)) counter Time.deltaTime transform.Rotate(Vector3.up rotateSpeed) Debug.Log("pressed D") if (!Input.GetMouseButton(1)) moveSpeed 20 if (!Input.anyKey) if (counter gt 2) StartCoroutine(Test()) anim.Play("Animation") counter 0 Debug.Log("A key or mouse click has been detected")


What's the proper way to use static objects and singletons in Unity? I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton using UnityEngine using System.Collections public class SceneStatics MonoBehaviour private static SceneStatics instance public static SceneStatics Instance get if (instance null) instance new GameObject ("SceneStatics").AddComponent lt SceneStatics gt () DontDestroyOnLoad(instance) return instance public void OnApplicationQuit () instance null I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that? Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent? Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics? Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)?


How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions? I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below. A projectile is organized into a container Projectile GO and two children GO a PhysicsColliders GO and a HitBoxColliders GO. The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders. The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger. Projectiles are set in motion by setting the velocity of the RigidBody once upon firing. Here is a visual of the structure ProjectileGO PhysicsCollidersGO HitBoxCollidersGO Here are descriptions of the GameObjects and their components ProjectileGO RigidBody2D Component (collisionDetectionMode is set to Continious) PhysicsCollidersGO (Layer is set to Projectile) BoxCollider2D Component HitBoxCollidersGO (Layer is set to HitBox) BoxCollider2D Component (IsTrigger is set) HitScript Component Problem 1. Projectiles will sometimes not collide with walls solid objects etc... Problem 2. Projectiles will sometimes not trigger a hit. What could be causing these inconsistencies? How can ensure that collisions and triggers will consistently behave correctly?


Collider does not call callback functions I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field. I check different tutorials and documentation and cannot find a way to do this in code. My code looks like objectToPlace (GameObject)AssetDatabase.LoadAssetAtPath("Assets Game 3D Models Buildings " objectName ".fbx", typeof(GameObject)) objectToPlace.SetActive(true) objectToPlace.transform.localScale new Vector3(1, 1, 1) objectToPlace Instantiate(objectToPlace) objectToPlace.transform.Rotate(Vector3.right 90) BoxCollider collider (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider)) collider.isTrigger true In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6? I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.


Draw trajectory arc predictor in game I found this tutorial on youtube and it works pretty well, but I want to add more to it. How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)? Here is the code public class BallLauncher MonoBehaviour public Rigidbody ball public Transform target public float h 25 public float gravity 18 public bool debugPath void Start() ball.useGravity false void Update() if (Input.GetKeyDown (KeyCode.Space)) Launch () if (debugPath) DrawPath () void Launch() Physics.gravity Vector3.up gravity ball.useGravity true ball.velocity CalculateLaunchData ().initialVelocity LaunchData CalculateLaunchData() float displacementY target.position.y ball.position.y Vector3 displacementXZ new Vector3 (target.position.x ball.position.x, 0, target.position.z ball.position.z) float time Mathf.Sqrt( 2 h gravity) Mathf.Sqrt(2 (displacementY h) gravity) Vector3 velocityY Vector3.up Mathf.Sqrt ( 2 gravity h) Vector3 velocityXZ displacementXZ time return new LaunchData(velocityXZ velocityY Mathf.Sign(gravity), time) void DrawPath() LaunchData launchData CalculateLaunchData () Vector3 previousDrawPoint ball.position int resolution 30 for (int i 1 i lt resolution i ) float simulationTime i (float)resolution launchData.timeToTarget Vector3 displacement launchData.initialVelocity simulationTime Vector3.up gravity simulationTime simulationTime 2f Vector3 drawPoint ball.position displacement Debug.DrawLine (previousDrawPoint, drawPoint, Color.green) previousDrawPoint drawPoint struct LaunchData public readonly Vector3 initialVelocity public readonly float timeToTarget public LaunchData (Vector3 initialVelocity, float timeToTarget) this.initialVelocity initialVelocity this.timeToTarget timeToTarget I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode


Drawing rectangle around a target on screen I am just started with Unity and C . I need in my work to do rectangle on a scene. I have a 3D scene, say some warehouse and there is an object. Camera is animated and moving towards the object. Is it possible to draw a rectangle around the object on the camera screen while the camera is moving unless the object on the screen? The task is like keeping target in war flight games. This is my code, where I tried to draw rectangle anywhere using System.Collections using System.Collections.Generic using UnityEngine public class MY getting images MonoBehaviour Start is called before the first frame update public GameObject pallet public Camera color cam public Vector3 pos LineRenderer l void Start() pallet GameObject.Find("PalletWood01") l pallet.AddComponent lt LineRenderer gt () List lt Vector3 gt ps new List lt Vector3 gt () ps.Add(new Vector3(0, 0)) pos pallet.transform.position ps.Add(new Vector3(10,10)) l.startWidth 1f l.endWidth 1f l.SetPositions(ps.ToArray()) l.useWorldSpace true Finding camera in a scene tag needed camera, for example "Player", and then GameObject.FindWithTag("Player").GetComponent lt Camera gt () Tag the camera another way for deployment color cam GameObject.FindWithTag("Player").GetComponent lt Camera gt () pos color cam.transform.position pos pallet.transform.position Debug.DrawLine(Vector3.zero, new Vector3(0, 0, 5), Color.red) Debug.Log(pos) Update is called once per frame void Update() Debug.Log(pos) pos color cam.transform.position Debug.Log(pos) The scene now looks like on the image above I want 2d rectangle around the pallet drawn on the screen.


How can I make the objects to move at the same speed as the lines? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) Vector3 endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, counter 500f speed) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) The lines are LineRenderer. void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.tag "FrameLine" myLine.name "FrameLine" myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () myLine.GetComponent lt EndHolder gt ().EndVector end LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace false lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, start) So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed. Now I want to move the instancesToMove (GameObject ) with the same speed as the lines but the instancesToMove are moving much slower then the lines. I tried instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed) Then instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed Time.deltaTime) But it's never moving with the same lines speed.


Encapsulating parameterised prefabs I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviours) public class MyComponent MonoBehaviour Configurable fields SerializeField private bool someParameter SerializeField private int anotherParameter Fake constructor to act as a replacement for GameObject.AddComponent with additional parameters. public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter) var myComponent gameObject.AddComponent lt MyComponent gt () myComponent.someParameter someParameter myComponent.anotherParameter anotherParameter return myComponent Public properties and other methods ... This works around the lack of constructors for MonoBehaviours but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built). Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them. So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation? (I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)


I want camera to be positioned on the player also x axis should move continuosly by .05f in unity 2d I am creating an 2d platformer and I am newbie to Unity any help will be highly appreciated. I want the camera to be positioned on the player and also the X axis should move continuously by .05f. And if player is not moving or stuck somewhere and if player is behind camera player (because X axis is automatically moving by .05f) then player should die. Is it doable? I am using Cinemachine and any script logic will be appreciated.


Set the start orientation of the gyroscope to initial phone orientation I am making a mobile VR project in Unity, and I have a 360 degree video that starts playing where I can look around using a VR headset. I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong. This is my code (on the camera inside the sphere) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Gyroscope MonoBehaviour private bool gyroEnabled private Gyroscope gyro private GameObject cameraContainer A camera container for my main camera private GameObject videoSphere The sphere my video is in private Quaternion rot private void Start() videoSphere GameObject.FindGameObjectWithTag("Video") cameraContainer new GameObject("Camera Container") gyroEnabled EnableGyro() cameraContainer.transform.position transform.position put the cameracontainer into the sphere cameraContainer.transform.rotation Input.gyro.attitude here I want to set the cameracontainer to the rotation of my phones gyroscope transform.SetParent(cameraContainer.transform) make my main camera a child of the camera Container videoSphere.transform.localRotation cameraContainer.transform.rotation Here I wanted to set my sphere rotation to the camera rotation Debug.Log(videoSphere.transform.localRotation) private bool EnableGyro() if (SystemInfo.supportsGyroscope) Input.gyro.enabled true turn on my gyroscope cameraContainer.transform.rotation new Quaternion(0, 90, 90, 0) rotate my camera container so the video shows good rot new Quaternion(0, 0, 1, 0) set the variable rot so that you can turn your device return true return false private void Update() if (gyroEnabled) transform.localRotation Input.gyro.attitude rot this makes you turn the device and it recognizes the input of the phones gyroscope


2 cameras that each player sees through a different one Im very new to Networking in Unity 5. Im trying to bring the finished basis for my 2 player, 1 vs 1, turn based game I made for local multiplayer (both players on same computer) to an online matchmaking system. In the game currently (for local), there are 3 cameras. 2 centered on separate canvases for selecting attacks for each player. that once p1 chooses his attacks and presses continue, the camera is deactivated and the 2nd camera for p2's attacks is activated. Once p2 presses to continue the 2nd cam is also deactivated and the 3rd cam is put on, this camera is set on the battle arena and plays out in turns the moves picked by the 2 players through a turn determining system. What I want to do for the online is have both canvas cameras activated at the same time and each player to be assigned to a different camera. So is there a good way i should do this? NetworkView on one of the cams? Hope I explained the premise enough P


How to use Input.GetAxis("Mouse X Y") to rotate the camera? I want to make a first person camera that rotates with the mouse. I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated! Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera? using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public float horizontalSpeed 2.0F public float verticalSpeed 2.0F void Update() float h horizontalSpeed Input.GetAxis("Mouse X") float v verticalSpeed Input.GetAxis("Mouse Y") transform.Rotate(v, h, 0)


How can I rig an object to animate from two different orientations? As an example Say you're animating a skateboard. The board has a nose and a tail. Normally, the nose points forward and the tail points backward. Now say you have two animations idle and trick. The idle is animated with the nose pointing forward. The trick, however involves the board rotating 180 , ending with the nose pointing backward, functionally swapping the nose and tail. Now, if you were to blend the trick animation back into idle, the blend would rotate the board back around so the nose points forward, which would not be the intended behavior. The intended behavior would be for the animator to somehow know that the tail is now the forward facing orientation and animate as if the tail were the nose. I'm competent but no expert with rigging animation and I've been racking my brain trying to come up with either a way to cleverly rig the object to somehow work as intended or to be able to modify the animations procedurally in code or something, but I haven't been able to figure it out. This seems like a problem that must come up somewhat frequently with game animation, but I haven't been able to find any specific resources. I'm using Blender and Unity. Edit To be clear, I'm not talking about root motion or the animating object's position rotation in the world, just the orientation of the bones being animated.


How to make the camera follow the mouse in first or third person camera I currently I have a game made of a few small scripts, the PlayerController, PlayerStats, and CameraChange (each below). My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse. Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that. PlayerController using UnityEngine public class PlayerContorller MonoBehaviour Update is called once per frame void Update () var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) PlayerStats using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStats MonoBehaviour public int Health 100 public int Stamina 100 public int magic 100 Use this for initialization void Start () Update is called once per frame void Update () if () CameraChange using System.Collections using System.Collections.Generic using UnityEngine public class CameraChange MonoBehaviour public GameObject ThirdCam public GameObject FirstCam public int CamMode Update is called once per frame void Update () if (Input.GetButtonDown("Camera")) if (CamMode 1) CamMode 0 else CamMode 1 StartCoroutine(CamChange()) IEnumerator CamChange() yield return new WaitForSeconds(0.01f) if(CamMode 0) ThirdCam.SetActive(true) FirstCam.SetActive(false) if(CamMode 1) FirstCam.SetActive(true) ThirdCam.SetActive(false)


Unity Custom Inspector Platform dependent property section I want to make a custom inspector for one of my scripts that builds UI elements at runtime. This requires small changes to the default values depending on what platform I'm targeting. How do I add something that is similar to the graphics settings where there is a default option but each platform is able to override the default setting for a platform specific value? I'm looking for the same kind of thing that Unity has for the player settings (Edit Project Settings Player). This allows you to set the details for each one but you can override them for each platform if they need to be different.


How do I dynamically use the rect tool in Unity2D? The rect tool in Unity2D (I honestly do not remember if it is present in Unity3D) allows you to scale down scale up an object in just one direction (what it does is it simultaneously increases decreases the height of an object in transform.scale and transform.position. I was trying to scale down an object while keeping its position the same using this code (P.S. I took the first four lines of code from here The Best Way To Generate a Random Float in C ) float range (double)float.MaxValue (double)float.MinValue float sample scaleRand.NextDouble() float scaled (sample range) float.MinValue float f (float)scaled if (f gt 0.6f) f 0.6f gameObject.localScale new Vector2(gameObject.lossyScale.x, (gameObject.lossyScale.y f)) However, this code does not work. So, how can I recreate the effect of using the rect tool in Unity Editor using C ?


Press and hold camera movement with mouse in new Input System? I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held. Here's how I did it before private void Update() Get the position of the mouse when a middle click occurs if (Input.GetMouseButtonDown(2)) dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) If the MMB is still held down, calculate the distance and move the camera if (Input.GetMouseButton(2)) Vector3 difference dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) cam.transform.position difference I have tried doing something similar in the new input system but it doesn't work public void OnMMB(InputAction.CallbackContext context) if (context.phase ! InputActionPhase.Started) Get the position of the mouse when a middle click occurs dragOrigin cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) else If the MMB is still held down, calculate the distance and move the camera Vector2 newPosition cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) Vector3 difference dragOrigin newPosition cam.transform.position difference Here is how I set this up inside the Input editor The Action Type of the action is Button.


Creating a delay by using Invoke Is it possible to delay the effects of a script that is attached to a game object? I have 2 characters in a scene, both receiving live motion capture data, so they are both animated identically. I have rotated one by 180 degrees and placed it in front of the other one, to create the impression that they are copying mirroring each other. Each has several scripts attached to them, of course... Now, I would like to be able to delay one character a bit (e.g. 1 sec) to make it look more realistic, as if one character is observing the other character and then copying its exact movements. Is it possible to do this by somehow using the Invoke method on the other character's Update perhaps? Or any other possibilities to achieve what I described? EDIT I used a buffering mechanism, as suggested by all the helpful comments and answers, instead of delaying, because delaying would have resulted in the same network data being used, except after a delay, but I needed the same old data being used to animate a second character to create the impression of a delayed copying... private Queue lt Vector3 gt posQueue private Queue lt Quaternion gt rotQueue int delayedFrames 30 void Start() posQueue new Queue lt Vector3 gt () rotQueue new Queue lt Quaternion gt () void Update() Vector3 latestPositions Quaternion latestOrientations if (mvnActors.getLatestPose(actorID 1, out latestPositions, out latestOrientations)) posQueue.Enqueue(latestPositions) rotQueue.Enqueue(latestOrientations) if ((posQueue.Count gt delayedFrames) amp amp (rotQueue.Count gt delayedFrames)) Vector3 delayedPos posQueue.Dequeue() Quaternion delayedRot rotQueue.Dequeue() updateMvnActor(currentPose, delayedPos, delayedRot) updateModel(currentPose, targetModel)


Flare (particle system) showing weird semi transparent rectangles instead of smoke when there's fog in the scene I'm making an FPS game with some fog in the scene. I've added a flare particle system (from the standard assets' prefabs) but it looks like it has some weird collision with the fog. Whenever the fog is enabled I get these weird rectangles on top of the flare like in this screenshot I've noticed that when I turn off the fog they disappear, also I've noticed that when I turn off the Emission part of the particle system the rectangles disappear, but of course, also most of the wanted effect is gone.


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!


Problem with Factory Method Pattern when I try to create a Weapon MonoBehaviour I'm learning about Design Patterns using Unity and I'm not sure about how to solve the following problem with the Factory Method Pattern I want to read a XML file and using the Factory Method Pattern to create a Component (a Weapon) to add it to a GameObject which will be cointained on a Pool Manager, but Weapon "Is A" MonoBehaviour and for that reason It can't be instantiated using a "machineGun new MachineGun() " public abstract class WeaponFactoryMethod protected string fileName "weapons.xml" public abstract Weapon CreateWeapon() public class MachineGunFactoryMethod WeaponFactoryMethod public override Weapon CreateWeapon() string filePath Path.Combine(Application.streamingAssetsPath, fileName) Weapon machineGun null XmlReader xmlReader new XmlTextReader(filePath) if (xmlReader.ReadToDescendant("Weapons")) if (xmlReader.ReadToDescendant("Weapon")) do I CAN'T DO THIS machineGun new MachineGun() machineGun.ReadXml(xmlReader) while (xmlReader.ReadToNextSibling("Weapon")) else Debug.LogError("There aren't definition for Weapon") else Debug.LogError("There aren't definition for any Weapon") return machineGun public abstract class Weapon MonoBehaviour, IXmlSerializable public float AttackRange get set Every weapons Shoots in a different way public abstract void Shoot() Serialization public XmlSchema GetSchema() return null public void ReadXml(XmlReader reader) XmlReader childReader reader.ReadSubtree() while (childReader.Read()) switch (childReader.Name) case "AttackRange" childReader.Read() AttackRange childReader.ReadContentAsInt() break public void WriteXml(XmlWriter writer) public class MachineGun Weapon public override void Shot() Raycasting.. At the end I want something like GameObject (player) Component (A Weapon script with the data from the xml) Should I just create a GameObject (player) and do an "AddComponent lt MachineGun " and later copy the info from the xml file instead using the Factory Method Pattern?? Is there a better way?? Any suggestions, corrections or advice will be very grateful. I'm sorry by my English.


Aspect ratios for sprites in Unity3d I'm using Unity3D version 5.0. I'm wondering what the best way to deal with changing resolutions in Unity is. In Swift I can just use the x2 x3 in order for it to pick the correct sprite for it to use. Is there a similar mechanism in Unity? Thanks


Unity Inaccurate rotation if object is rotated on two axis at once I have an object which i want to rotate relative to world space. I have three variables (one for every axis) which store the rotation. By pressing buttons on my controller I add or subtract 90 to these variables (rotX, rotY, rotZ). Then I rotate my Object like this transform.Rotate (rotX delta, rotY delta, rotZ delta, Space.World) As this is called every frame the object would spin forever so i subtract the ammount I've allready rotated afterwards rotX rotX delta rotY rotY delta rotZ rotZ delta This works fine as long as I don't rotate two axis at once. Then the object rotates rotates only partially to the desired position (e.g. 83 if I want to rotate to 90). I can't see what I've done wrong. It actually seems like the moment I start an rotation around an axis all other axis get canceled. But if I monitor the variables they look exactly as they should. Thank you in advance and have a amazing day!


Configurable Joint how to create a FixedJoint, and Rotating it? I have 2 rigidbody, in 2d view, non kinematic, and with no gravity, and want to connect them with a Configurable joint. I don't want the joint to be spring (I want the same distance always). But I would like to move the blue object left right (rotating it around the red one) How can I setup my Configurable Joint ? Thanks you !


How can I send commands to only certain clients? I am building a multiplayer game server with Unity. In the game there are players moving around the map. Now, because this map is quite large compared to the number of players, I was thinking to have the server send each clients' position only when they are nearby, and then slow the rate down when they are far away. At first I was using the convenient SyncVar to do sync everyone's position, until I discovered its shortcomings, that is there is no conditional way to either sync or not a certain value. I came out with this player synchronization class so far (I removed all optimizations for simplicity) public class PlayerSyncPositionConditional NetworkBehaviour Vector3 lastPos void FixedUpdate () TransmitPosition() ClientCallback void TransmitPosition () CmdProvidePositionToServer(transform.position) Command void CmdProvidePositionToServer (Vector3 pos) transform.position pos Now, what this code does is nothing more than sending its position to the server when I am looking at the dedicated server instance, each players' position is correct. Also, as expected, each client will not receive any updates. From my research, I found that instead of SyncVar, I can use Server and ClientRpc to dispatch commands from the server to all clients, so this Server public void MoveTo() RpcMoveTo(transform.position) ClientRPC void RpcMoveTo(Vector3 newPosition) transform.position newPosition this will run in all clients would move all clients to the transform current position whenever needed. Now, the problem is that those commands, apparently affect every client, while I only want to affect ones that are near each other. I know how to have the server issue the MoveTo at any rate I want, setup more than one interval, etc. but I don't know how to have it send only to certain clients at a single time. I am not asking for the code itself, but I am getting really confused with all these client server architecture concepts, which class does what, etc. so any heads up will be greatly appreciated.


Disabled script works anyway I have a simple code that will be enabled when I kick, so I disable it right away but even though it is disabled, it works somehow. can it be because of his parent or something else I dont know of? this is the script Kick Test, i dont reach it from anywhere else private GameObject ball private Rigidbody2D rg2d public int power 30 void Start() ball GameObject.FindGameObjectWithTag("Ball") rg2d ball.GetComponent lt Rigidbody2D gt () this.enabled false private void OnTriggerEnter2D(Collider2D col) if(col.tag "Ball") Debug.Log("K CK") Vector2 pos (transform.position col.gameObject.transform.position).normalized rg2d.AddForce( pos power, ForceMode2D.Impulse)


Can a prefab of a complete Unity scene be created? Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.


How to play an animation backwards in Unity? I know this question has been asked before but it all involves using the Animation(?) component, so that is no longer any good in Unity 5.3.1f1, I explain a bit more later. I'm trying to simply get an animation to play backwards. On the object that I want to have an animation play backwards on, I have an animator. private Animator anim ... anim GetComponent lt Animator gt () If I do animator.speed 1.0f It tells me Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode ! AnimatorRecorderMode.Offline So I try putting on an Animation component on the game object, and making the clip the animation. Every time I do anything with the Animation component in script, it tells me the component must be marked as Legacy. That is no good, because when I tried making it Legacy it caused multiple problems including not being recognized by the Animator. Also GetRef errors. The entire Animation component seems like it's treated as legacy now or is just broken. So I decided well maybe I could just try to get the animation to play backwards in the animator and having the animator record it, and then using that backwards recorded animation in the actual game. I cannot figure out how to this, even if I click record in the Animation view anim.recorderMode ! AnimatorRecorderMode.Record. I don't know what to do. All I want to do is play the same animation backwards without having to copy and paste an animation in the Project and moving all of the keys around so that they are reversed. Please help. Unity's animation system seems so convoluted in script.


UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?


Follow a path in Unity I want to know how I can make this game object follow the specified path in unity


Photon2 billboards take a long time to face the camera I'm using PUN2 and trying to use nametag billboards for my players, but they are not facing forward correctly and I have to wait more than 20 seconds to make the name tag of player return to facing forward. here's my code for my BillBoard Script public class BillBoard MonoBehaviour protected Transform ThisCameraPlayerBillBoard private void Start() ThisCameraPlayerBillBoard GameSetup.GS.ThisCameraToBillBoard.GetComponent lt Camera gt ().transform private void FixedUpdate() transform.LookAt(transform.position ThisCameraPlayerBillBoard .rotation Vector3.forward, ThisCameraPlayerBillBoard .rotation Vector3.up)


How to block the player from moving left and right from two empty game objects? I made the game space shooter in that game my spaceship move left and right but its not stop in right and left corner. When its move to left its go out of the screen. how i stop block in the left and right screen edges. using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speedMove 3 public float bonusTime private Rigidbody rb private float limit 3 1 for right and 1 for left. private float direction 1 You can call it as speed private float speed 0.01f private bool toLeft false private bool toRight false public GameObject shield public GUIText bonustimeText private bool counting true private float counter private Weapon addWeapons public Sprite strongShip public Sprite normalSprite public Sprite shieldSprite private SpriteRenderer sRender private Weapon weaponScript void Start () counter bonusTime rb GetComponent lt Rigidbody gt () sRender GetComponent lt SpriteRenderer gt () addWeapons GetComponentsInChildren lt Weapon gt () foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript GetComponent lt Weapon gt () weaponScript.enabled true Update is called once per frame void Update () transform.position Vector3.MoveTowards (transform.position,new Vector3 (transform.position.x direction, transform.position.y, transform.position.z), speed) if (Input.GetMouseButtonDown (0)) direction 1 void OnCollisionEnter2D(Collision2D coll) if (coll.gameObject.tag "StrongMode") Destroy (coll.gameObject) counting true StrongMode() Invoke ("Downgrade", bonusTime) if (coll.gameObject.tag "ShieldMode") Destroy (coll.gameObject) counting true ShieldMode() Invoke("Downgrade", bonusTime) if (coll.gameObject.tag "Life") GUIHealth gui GameObject.Find ("GUI").GetComponent lt GUIHealth gt () gui.AddHealth() SendMessage("AddHp") SoundHelper.instanceSound.PickUpSound() Destroy(coll.gameObject) if (coll.gameObject.tag "Enemy") SendMessage("Dead") void Downgrade() SoundHelper.instanceSound.BonusDownSound () counting false bonustimeText.text "" counter bonusTime sRender.sprite normalSprite weaponScript.enabled true foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript.enabled true shield.SetActive (false) void StrongMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite strongShip foreach (Weapon addWeapon in addWeapons) addWeapon.enabled true weaponScript.enabled false void ShieldMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite shieldSprite shield.SetActive (true) void OnDestroy() bonustimeText.text ""


How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script using UnityEngine using System.Collections public class hu MonoBehaviour GameObject pauseObjects public bool isPaused void Start () pauseObjects GameObject.FindGameObjectsWithTag("Player") Update is called once per frame void Pause () if(Time.timeScale 1) Time.timeScale 7f else if (Time.timeScale 8f) Time.timeScale 1


How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?


Unity, Cannot See Items on the Scene I am new to unity. I have created an asset by using Blender and managed to put it in the scene. But somehow now I can only see one item at a scene. For example I can only see camera when I clicked "Main camera" at the Hierarchy toolbar. When I clicked the asset, the camera is hidden from the scene along with lighting etc. This is difficult for me since I need to put my asset in front of the camera. Where can I toggle back the views for everything in the scene?


How to tilt an object(2D) after collision and the rotate continuously I am having trouble rotating and object after collision. The object only transforms to the given angle of rotation once and stops. I would like to achieve in a way that after it has collided with the player object it rotates continuously till its killed after exiting the screen. The OnCollisionEnter2D(Collision2D collision) can't achieve this. How can I achieve it using the FixedUpdate function? Here is the code namespace Assets.scripts public class Barmovementscript MonoBehaviour public float Tilt private void FixedUpdate() upon collision the object rotates in a clockwise direction. void OnCollisionEnter2D(Collision2D collision) if (collision.collider.tag "Player") Tilt Time.deltaTime 10 gameObject.transform.rotation Quaternion.Euler(0, 0, Tilt)


How to display custom UnityEvents in the editor? I recently stumbled upon the UnityEngine.Events.UnityEvent class, and it seemed pretty cool so I started using it in a project. Then I decided that I wanted to add some parameters to the event using its generic variants, like so System.Serializable public class BarkEvent lt GameObject gt UnityEvent lt GameObject gt public class MyOtherClass MonoBehavior public BarkEvent lt GameObject gt bark ... Other stuff ... But now it doesn't show up in the editor, making it harder to wire up my subscribers. Is there a way to make unity events with extra arguments show up in the Unity editor?


With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D? So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with TileRenderer.material.SetTextureScale(" MainTex", new Vector2(0.25f, 0.25f)) TileRenderer.material.SetTextureOffset(" MainTex", new Vector2(0 0.25f,0)) but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.


Unity5 using non convex meshcollider with rigidbody I want to build a car using wheel collider, mesh collider and rigidbody. The problem is that unity wants the meshcollider to be convex, and that cannot happen because my base model is bigger than 255 poly's.


How to make an expanding radial search in Unity? I am currently working on a City Builder Game and I often come across the problem of having to decide wich location to use. Examples The citizen has a job and needs a home. There are several buildings with open slots. The citizen is at a positon and is hungry. There are several restaurants on the map. How can I choose the right building to go to? I don't really wan't to check the distance for each, because there could potentially be hundreds of buildings and that decision problem occurs quite often. I also don't care for the optimal solution, any nearby result is fine. Currently all buildings register them self in a LinkedList. When searching for something I'd start at the beginning and the first occurrence that was 'good enough' would be returned. Citizen now drive across the map for something that was right next to them if the one far away was built earlier in the game. Any suggestions?


How to seamlessly handle multiple procedural 2D levels in Unity3D? I have a dungeon generating algorithm, but I would like to generate X levels, which are all connected somehow. I have a few approaches, but all of them has problems and questions, and I wonder how i.e. Diablo II handles them so seamlessly. 1. Approach Upon leaving a level, generate the next one on the fly. This would be the easiest, but would result in a relatively long loading screen everytime the player enters a new level. So generating the levels should be at the beginning of a new game, thus the next level will just have to be loaded, which is much faster. In theory not even a loading screen is necessary. 2. Approach Generate every level at the beginning of a new game and store them. Okay, now levels just have to be loaded, which could be done under half a second. No loading screen is necessary, maybe just a fade out fade in. How do I store them? Make custom files (i.e. scriptable objects) for them, or is there a simpler way? 3. Approach Generate and load every level at the beginning. Zero loading time, because everything is already generated and loaded into the tilemap. But how do I guarantee that levels don't collide, and the player can't see level Y from level X if there are lots of levels? And wouldn't it affect the performance? Because everything is loaded all the time. Yes, renderers, rigidbodies, scripts, etc can be turned off, improving the performance a lot... but still... this seems wrong. What is the best way to solve this problem?


How to check if a test ad is ready I was going through UnityAds for Unity3D, and came across this setting AD TEST MODE Force all So as I understood it states that I will be able to see real ads, in test mode, without monetizations on my testing tool, which in my case is Unity3D IDE, but I am still getting that blue sample ad screen quot Here would be your ad screen quot . Is there anything that I can do to check if any ad is placed for my app, and check this via code before Advertisement.Show() statement? Or am I missing something?


What is the most efficient technique for range detection? I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range a specific radius. Which method is the most efficient and elegant? overlapSphere sphereCast triggers square magnitude anything else? I am using Unity.


Trouble with Inventory System and Item References I'm currently trying to get a simple inventory system to work but I'm having a lot of trouble. This isn't the exact code I have, but it's a shorter version that I'm pretty sure would function the same public struct ItemSlot public Item item public ItemSlot(Item item) this.item item public class Item MonoBehaviour public string itemName public class Accessory Item public class Inventory MonoBehaviour public ItemSlot itemSlots new ItemSlot 1 public void AddItem(ItemSlot slot) itemSlots 0 slot public class Player MonoBehaviour public Inventory inventory private void Update() if (Input.GetKeyDown(KeyCode.E)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(ray, out hitInfo, 20)) GameObject target hitInfo.collider.gameObject inventory.AddItem(new ItemSlot(target.GetComponent lt Item gt ())) Destroy(target) if (Input.GetKeyDown(KeyCode.G)) print(inventory.itemSlots 0 .item) For a bit more prefacing I have a capsule object with the Player script on it, an empty with the Inventory script on it, which is then attached to the Player script (I'm not sure if I want to make the inventory a scriptable object which is why I've done this), and then lastly I have a cube object with the Accessory script on it. So, when I press E and pick up the item it gets added into the player's inventory and then destroyed from the scene. Then, when I press G to display that item in the inventory the console just says null. Not Null, which is what an actual null would show up as, but the string "null". If I use visual studio's debugger and have a look at what the accessory's base is, it also says null, but for some reason if I then try and print the accessory's name then that works fine, even though that variable is defined in the Item class. If I instead do this in the Inventory class public void AddItem(ItemSlot slot) ItemSlot 0 slot print(ItemSlot 0 .item) It works fine and prints Item (Accessory) in the console. Even if I print it right after I destroy target in the Player class, that also prints Item (Accessory), so I have no idea why it doesn't work on the next block of code. Sorry this is so long and maybe an easy fix, but I'm lost. Edit I think everything should be fixed now.


How to clip what is outside scroll view when using a custom UI element? I have created a custom UI element (that use CanvasRenderer). Here is code Mesh mesh new Mesh() Rect drawArea GetComponent lt RectTransform gt ().rect using (VertexHelper helper new VertexHelper()) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMin), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMin), Color.white, Vector2.zero) helper.AddTriangle(0, 1, 2) helper.AddTriangle(2, 3, 0) helper.FillMesh(mesh) var canvas GetComponent lt CanvasRenderer gt () canvas.SetMesh(mesh) canvas.SetMaterial(Material, null) It creates a simple rectangle that is same size as rect transform. It works great. However if I put this inside a scroll view, everything that is outside scroll area viewport is rendered (while it should be clipped). The scrolling works as it should (rectangle get scrolled by changing position when scrollbar is used). I have tried to call canvas.EnableRectClipping(...) but without success.


When using IK the player head is looking at down the ground instead looking at the object target up what can be the problem? This script is attached to the player using UnityEngine using System using System.Collections RequireComponent(typeof(Animator)) public class CharController MonoBehaviour protected Animator animator public bool ikActive false public Transform lookObj null public float lookWeight 2f void Start() animator GetComponent lt Animator gt () a callback for calculating IK void OnAnimatorIK() if (animator) if the IK is active, set the position and rotation directly to the goal. if (ikActive) Set the look target position, if one has been assigned if (lookObj ! null) animator.SetLookAtWeight(lookWeight) animator.SetLookAtPosition(lookObj.position) if the IK is not active, set the position and rotation of the hand and head back to the original position else animator.SetLookAtWeight(0) When the lookObj is a sphere or a cube it's working fine but if the lookObj for example is a big spacecraft now the player head will look to the ground down and not to the spacecraft up The problem is that the center of the spacecraft is at the bottom this is a screenshot when it's showing the spacecraft at regular when it's in Pivot mode Now when I click on the Center button now the center of the object is at the bottom Is there any way to fix it maybe eve fix it ?


How to adjust Unity banner ads for IOS? I'm using Device Simulator from the package manager to test on mobile devices. I'm using a banner ad at the top center with the code Advertisement.Banner.SetPosition (BannerPosition.TOP CENTER) For andoid devices I can see it but on IOS devices it is blocked by its top notches or the safe area the Device Simulator calls it. Is there a way to reposition the y axis to fit on IOS devices? Thanks


SmothStop Function doesn't work as expected i'm trying to create a smothstop function i need it to control time variable on my lerp function used to move character and so on...what i have is this private float SmothStop(float t) return 1 (1 t t t t t) problem here is that will start slow then accelerate... same as smothstart function.. that i already tested and work on that way.. so.. what i'm missing up?


Limiting x and y movement so you can't go off camera So I want to make an on rails shooter like that of Star Fox in the Unity engine. What I would like to do is limit the ship from moving off the screen. You move along the X and Y axis so i wont have to keep these invisible colliders in their place but I cant get another way to work. and I know I have to find a way to convert camera space to world space I just can't find a way how. This is my current controller and I commented a few failed attempts. also I'm using a perspective camera and I'd like to keep the rigibody movement if possible. public float turnSpeed 10 Horizontal private Vector3 moveDirection Vector3.zero public Rigidbody rb void Start() rb GetComponent lt Rigidbody gt () void Update() Screen.width transform.position new Vector3(Mathf.Clamp(transform.position.x, holdMyRatio, holdMyRatio), Mathf.Clamp(transform.position.y, holdMyRatio, holdMyRatio), 0) CharacterController controller GetComponent lt CharacterController gt () rb.AddRelativeForce(Vector3.right turnSpeed Input.GetAxis("Horizontal")) rb.AddRelativeForce(Vector3.up turnSpeed Input.GetAxis("Vertical")) moveDirection.x Input.GetAxis("Mouse X") turnSpeed Time.smoothDeltaTime moveDirection.y Input.GetAxis("Mouse Y") turnSpeed Time.smoothDeltaTime controller.Move(moveDirection Time.smoothDeltaTime)


Unity problems with OnTriggerStay and Input.GetKeyDown Background information Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire. Problem What the problem momently is, is that when I press the E key, it will fired the input more then one time. This is because I use a OnTriggerStay2D function, to check every second if my Player is collide with the campfire object. Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool and set it to true on OnTriggerEnter2D. But this isn't working for me. The same problem as before will occur. Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object. Also tried it with if(Input.GetKeyDown(KeyCode.E)) isTrigger true and the same for GetKeyUp, but then isTrigger false My current working code public Animator anim public int campfireStatus bool inTrigger false Use this for initialization void Start () anim GetComponent lt Animator gt () Update is called once per frame void Update () anim.SetInteger("Intensity", campfireStatus) void OnTriggerEnter2D(Collider2D other) inTrigger true void OnTriggerExit2D(Collider2D other) inTrigger false void OnTriggerStay2D(Collider2D other) If player comes in contact with gameObject if (other.gameObject.tag "Player") print ("player") if(Input.GetKeyDown(KeyCode.E)) print ("E Pressed") if (WoodBehaviour.count gt 0) campfireStatus So when the Player is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour script, that is linked to the player object ) than it should increase the campfireStatus with plus one. The problem is, that the if statements will fired more then one times when pressing the E key.


Managing shared dll correctly in Unity I'm developing a dll that is to be used in two Unity projects. I've read that the way to reference a dll is to drag it into a 'plugins' folder so that it is added to the Unity project's dependencies, as their is no "add reference" available for this project in Visual Studio. But doing that the Unity project does not take into account that the dll evolves (as it is still in development). What I'd like (if possible) is to set up an automatic way so that the Unity projects update their dependencies when the shared dll is updated. I've try the reimport option (right click on the dll in Unity) but it seems that it is not working. What is the best way to manage this situation?


Issues using NetworkServer.Spawn with Unity and Mirror Networking I am using Mirror to handle the networking aspect When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object. However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal? Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second. using System.Collections using System.Collections.Generic using UnityEngine using Mirror public class EnemySpawner NetworkBehaviour public uint theId public int maxNumEnemies public int spawnDelay public GameObject enemyToSpawn float curSpawnTime BoxCollider2D boxColl Start is called before the first frame update public override void OnStartServer() curSpawnTime spawnDelay boxColl GetComponent lt BoxCollider2D gt () void Start() if (!isServer) return theId netId Update is called once per frame void Update() if (!isServer) return if (transform.childCount lt maxNumEnemies amp amp curSpawnTime lt 0.0f) Vector2 spawnPoint new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y)) curSpawnTime spawnDelay SpawnEnemies(spawnPoint,netId) else curSpawnTime Time.deltaTime Server void SpawnEnemies(Vector2 spawnPoint, uint theId) GameObject gobj Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity) gobj.GetComponent lt EnemyController gt ().parentNetId netId NetworkServer.Spawn(gobj) The way I've organized things, in the hierarchy I have Enemies Area1 Spider(Clone) Spider(Clone) Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.


Drawing circles at the background of a 3D scene and updating their size So, here is what I am trying to do in Unity 5 (using C ). I want to draw a a 2D circle at the background of a 3D scene and apply a texture image to fill it. Just like it would be if the circle was in the GUI, but now being always behind everything else instead of always in front (think of a moon in the sky of a piloting game, or a distant planet in a space game, etc). What would be the fastest way to draw such a circle and, of course, update its radius depending on the camera distance? Of course, I don't want to use a sphere, I want to learn how to that with a simple circle that gets bigger or smaller depending on the distance of the viewer.


High poly vs Low Poly when creating model I am new in game development, but I have some knowledge in Maya and 3ds Max, I want to create pirate ship for game. So I spoke with many 3d artists and there are different opinions about low polygons and high polygons modelling. I am an iOS developer too so I know that it's hard for computer to process many polygons, so we should reduce amount of faces as much as we can. But my question is much more connected to 3D. Do I need to create low polygons model at start and then smooth it to increase amount of faces or do I need to create high polygons model and then reduce amount of edges, faces and etc?


How can use a 3D map with 2D characters (Unity)? I tried to search something about it but I can't find any complete or well explained tutorials about how to use a 3D map with 2D characters and items, like Ragnarok or Final Fantasy Tactics. If there is no tutorials about this topic, are there any recommendations for studying the subject? I've already developed some games using XNA, but only 2D games, I've never tried to use 3D models, nor have I used Unity to develop games.


Rotating fps rigid body on the Y axis I'm currently attempting to make a first person character using a rigid body. I am aware that the character controller exists, but I believe my game will be very physics based so it's better if my character is a rigid body. I currently can walk, and rotate the camera up and down with the mouse. I am now trying to rotate my character left and right with the mouse, but this requires me to rotate my rigid body, not just the camera. Here's my code so far. using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField float walkSpeed 3 SerializeField float cameraSpeed 3 Vector3 direction float cameraX Rigidbody myRigidBody SerializeField Camera myCamera Start is called before the first frame update void Start() myRigidBody GetComponent lt Rigidbody gt () Update is called once per frame void Update() direction new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) cameraX Input.GetAxis( quot Mouse Y quot ) cameraSpeed myCamera.transform.Rotate(new Vector3(cameraX, 0, 0)) void FixedUpdate() myRigidBody.AddRelativeForce(direction walkSpeed, ForceMode.Acceleration) I believe that the rigid body function I should use to rotate left and right is MoveRotation (I'm still new to rigid bodies), but I'm open to ideas. MoveRotation uses Quaternions, and I have no idea how to translate my mouse axis into a quaternion. Here's my question, How do i implement the Y rotation for my rigid body first person controller? Should I use torque, or somehow directly alter my rotation without using forces? Also, How do i translate the Mouse Axis into something I can use to rotate something? thnx. Edit I tried adding this line of code myRigidBody.MoveRotation(Quaternion.Euler(0, mouseX cameraSpeed, 0)) for some reason it has no effect on my character at all, but I feel Like it's on the right track. Why isn't this working? Edit 2 I added this line in Update rotateDirection new Vector3(0, Input.GetAxis( quot Mouse X quot ), 0) And this line in FixedUpdate myRigidBody.MoveRotation(Quaternion.Euler(rotateDirection)) Now when I move my mouse (I commented out my camera up and down movement to test) my character moves left and right for a tiny bit, but jitters back to it's original position, so It feels like I'm fighting it. The rotation in the inspector jitters in the correct direction, negative if i move the mouse left, positive if right, but only for a very small amount, 1.45 being the most, and then reverts back to zero. Also, it doesn't rotate smoothly, but jitters. Anybody know whats going on? Edit 3 changed it from addforce to addrelativeforce because that make it move forward based on local coordinates not global.


Unity Why do my 2 gameObjects 'share' materials? no one has answered this on Unity answers yet so I thought I might as well ask this here recently, I imported my .blend game character and the character consisted of 2 colors Red and black. Therefore as unity always does it creates 2 red and black materials for the colors of the character. Then, I imported the grass platform for my game. Because the grass platform is green and brown, Unity should have created 2 new green and brown materials and the platform should have stayed green and brown. But, instead, my grass platform decided to use my character's materials and my platform is now red and black. (If I import the grass platform first, my character becomes brown and green). Please help, this is an extremely annoying problem, thanks!


Move camera from wherever camera is to pinned point So, I need to switch move animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move). This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened. I tried to animate camera to position, camera just goes crazy. Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects position. I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work. Enable Disable Code public var door DoorAnim public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) Debug.Log("Door 1 built") camera1 GameObject.Find("Camera1") camera1.enable false camera2 GameObject.Find("Camera2") camera2.enable true door GameObject.Find("door1") door.animation.Play()


Is there a way to check if an object is currently colliding with anything? I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger). So, for my purpose, I don't need OnCollisionEnter OnTriggerEnter events, but I need something like this if ( myObject.isOnCollision ) do something How can I do this?


How to properly interact with game objects in Unity3D? I am trying to make a game where player will be placed in the scene and the goal is to explore it. He can interact with game objects that player can find in the environment, like picking object, examining, dropping and putting back. Basically it is something like first person exploration... So the problem is how to properly implement code regarding interaction. One way I see and saw it on the internet is Raycasting. So the idea would be to in Update() method place Raycast fire code and see what it hits. Also all game objects with which player can interact are placed on separate Layer and also limit length of Raycast (which is obvious thing to do as player cannot interact with objects that are like 10 meters from him)... So as I understand, game objects should have at least some kind of collider (I know box and sphere colliders are simple, but sometimes I will need to use more complex one)... That being said, I wonder is this right approach Separate layer for interactable objects Raycast that checks objects in that layer Raycast length limited to like 1 meter This approach should not be that much CPU consuming or is there any other way? I am also thinking to putting some invisible box area (trigger) where raycasting would make sense, but I am not sure will this be overhead or not.... So, at the end what would be the right approach to this?


Need help with physics 2D Unity I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches. With the code that i have right now, the rocket instantly rotates towards the point and moves there straight. Vector3 dir targetPos transform.position float rotZ Mathf.Atan2(dir.x, dir.y) Mathf.Rad2Deg rb.MoveRotation( rotZ) thrust 10.0f rigidbody2d.AddForceAtPosition(transform.up Thrust, transform.up) This code is placed in the Update function. I want the rocket to start moving in which ever direction It's currently facing and slowly rotate towards the point as it goes there.


How to get the loudness of the real world environment using the device's microphone in Unity? I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly. What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character. Is there such a function or if not how can I make one?


Unity3D Cancel a build process (Windows, Unity 5) I accidently pressed build for iOS and just realized that it might take a few hours to build the project. I tried to kill the unity process in the task manager, but on next start up unity instantly starts to build it again. Is there any option to cancel the build?


How can I plug a Unity application into native Android and native iOS? There are a lot of questions about running native Android and iOS code in Unity. I am trying to run Unity inside of native Android and native iOS apps. My problem is that I have two native apps, and I don't want to write code twice when I add a feature. I currently have two native apps one in Android and one in iOS. I am trying to write code once, and add it to both. Can I write a Unity program, and put that into my native apps? I am thinking something along the lines of writing a Unity Android app, building it as an Activity instead of an APK, and launching that Activity from the native android app. Then also the equivalent in iOS, whatever that may be. Does anyone know a solution to this problem?


Unity Blender models animations showing gaps As part of a college project, a member of my group has made some simple chests with an open animation. Importing these into Unity though, I instantly noticed there were gaps where the faces should be. After a bit of experimenting, I figured it was because the Normals were facing the wrong way. The outside seemed fixed, but faces were missing when the chest opens during its animation. I'm guessing the inside of the chest will need another layer of faces with the Normals facing the right way...? Though surely this would means having doubles...?


Download Progress bar from Firebase Storage Im trying to make a progress bar based on downloaded images from Firebase storage, now firebase does provide a snipper which works per image Create local filesystem URL string localUrl quot file local images island.jpg quot Start downloading a file Task task reference.GetFileAsync(localFile, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) task.ContinueWithOnMainThread(resultTask gt if (!resultTask.IsFaulted amp amp !resultTask.IsCanceled) Debug.Log( quot Download finished. quot ) ) but i would like to make that appear on a UI text based on the percentage of the Bytes downloaded like starting from 0 to 100 .Now i have come to this function so far which does work in the sense of downloading from storage and i do get the percentage in the console but im not sure how to convert that to a percentage to show on UI. if (CheckConnectivity) if the device is connected to the internet, initiate download. Debug.Log( quot Initiating download of quot platform file) if (!File.Exists(localPath)) Task task storageRef.GetFileAsync(localPath, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) await storageRef.Child( child).Child( file).GetFileAsync(localPath).ContinueWithOnMainThread(files gt if (!files.IsFaulted amp amp !files.IsCanceled) if download is successful. Debug.Log( quot file saved as quot localPath) else otherwise report error. Debug.Log(files.Exception.ToString()) ) else Debug.Log( quot files Exist quot ) else otherwise don't bother. Debug.Log( quot Cannot Download file due to lack of connectivity! quot ) in which case my debug is this Progress 1731 of 52804 bytes transferred. Which i would like to say 0 and counting up to 100! Thanks!


Handmade Terrain vs. Terrain Engine in Unity? I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side. I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev only rendered 3D video stills for other applications, so this is a learning process.


Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0)


Efficient way to implement a lot of singletons I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager. Is there a more efficient way to do it rather than pasting the pattern on each awake method?


Position GUI Text in 2D game I am working on a 2D game, and my camera is a orthographic with a size of 320. I want to display some text, but not with OnGUI(). Rather, with a GUI Text game object. I couldn't help but notice that positioning my GUI Text object is a real pain apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen. If I wanted to put my label at exactly (100,50) regardless of the screen size, I would have to calculate something like (100f Screen.width, 50f Screen.height) Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...


Cutout fragment shader pixels arent square It has been solved, link to the final shader Shader The problem (as portrayed by the image below) is that the pixels seem to be, for lack of a better word, cut off. I wish to either display a pixel, or not. My fragment function, it uses the red value of the vertex colors (displayed by the image blow) on the edge of the mesh which are assigned during mesh generation to determine the pixel cutout "weight" by multiplying it with the texture. fixed4 frag (v2f i) SV Target fixed4 tex tex2D( MainTex, i.uv) if (i.color.r tex.r gt 0.4f) discard return fixed4(tex.rgb clamp(i.color.r, 0.3f, 1.0f), 1.0f)


Moving a character according to the animation, rather than code I'm using 3ds Max to export character animations in which my character is moving. I expected this to mean that the character will move in Unity, but it doesn't... For example, if my animation (in 3ds Max) moves my character forward for a second, from 0,0,0 to 1,0,0, in Unity, the character snaps back to 0,0,0 once the animation ends. Is there a way to change the position of the character according to the animation, without something like CharacterController.Move?


Why does my Unity animator state "finish" before the visible motion does? Example The TopAppearing motion boost the alpha of the sprite from 0 to 1 for total of 2 seconds After TopAppearing state has been finished The TopAppearing's transition settings Question Why is the Top's sprite alpha 235 after the TopAppearing animatior state has been finished?


Spatial Jitter problem in large unity project I have a very large environment where i am getting very weird view of objects as picture given below As you can see there are black lines spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position 17000, 0, 144) As a workaround i tried to change my shader to Unlit and i found this shader Shader "Unlit UnlitAlphaWithFade" Properties Color ("Color Tint", Color) (1,1,1,1) MainTex ("Base (RGB) Alpha (A)", 2D) "white" Category Lighting Off ZWrite Off ZWrite On uncomment if you have problems like the sprite disappear in some rotations. Cull back Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater 0.001 uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels. Tags Queue Transparent SubShader Pass SetTexture MainTex ConstantColor Color Combine Texture constant This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.


ScreenToWorldPoint and ViewportToWorldPoint I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint amp viewportToWorldPoint. The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is. Code using System.Collections using System.Collections.Generic using UnityEngine public class ArmRotation MonoBehaviour public int rotationOffset 0 Update is called once per frame void Update () Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position Gets the difference between difference.Normalize() Normalizing the vector float rotateZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(0f, 0f, rotateZ rotationOffset) I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https answers.unity.com questions 168156 screen vs viewport what is the difference.html Where Screen from 0,0 to Screen.width, Screen.height Viewport from 0,0 to 1,1 Questions Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm instead of just setting the following . Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) I've tried setting it to the position of the mouse cursor instead of using the difference between the arm amp the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue? Why do we call difference.Normalize() ? To my understanding, Normalize returns a vector between 0 amp 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y x. As such, calling Normalize and returning a vector to a value between 0 amp 1 makes no difference because the value calculated will be the same between a un normalised and normalised vector since the proportions are the same? When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 amp 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. Why is this so? I would appreciate any help or pointers in the right directions. Thanks! EDIT I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused


How do I expose a field with a generic class to the Inspector? I have some utilities implemented as generic classes. I would like to have fields of these types exposed to the inspector but they appear to not display. This test code Serializable public class TestGenericClass lt T gt public string testField public TestGenericClass(T testValue) testField testValue.ToString() Serializable public class TestNormalClass public string testField public TestNormalClass(string testValue) testField testValue public class MonoBehaviourClass MonoBehaviour public TestGenericClass lt string gt testGenericClass new TestGenericClass lt string gt ("generic") public TestNormalClass testNormalClass new TestNormalClass("normal") Produces this result As you can see the field for the generic class is missing. How can I expose a field with a generic class to the inspector?


Help understanding IEnumerator Move routine I have this code and I know what it does (it will move an object up and down) But I don't know how its elements work. Could someone please explain it to me? IEnumerator Move (Vector3 Target) What this IEnumerator do? while (Mathf.Abs ((Target transform.localPosition).y) gt 0.1f) Vector3 Direction Target.y Top.y ? Vector3.up Vector3.down Is this an if else? and if yes why if target.y top.y its first choice is vector3.up? transform.localPosition Direction 5 Time.deltaTime yield return null yield return new WaitForSeconds(1f) Vector3 newTarget Target.y Top.y ? Bottom Top Same line but result order is different ?.? StartCoroutine(Move(newTarget))


Generate 4 vectors rotated in cardinal directions from a central vector There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together". Here is a visualization of what I need Test code is attached using System.Collections using UnityEngine public class Test MonoBehaviour public GameObject centerGO public GameObject leftGO public GameObject rightGO public GameObject backGO public GameObject frontGO ArrayList list new ArrayList() void Start() SetCenterPoint(Vector3.up) void Update() DrawDebugRays() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) SetCenterPoint(hit.point) void SetCenterPoint(Vector3 point) Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center centerGO.transform.position center leftGO.transform.position left rightGO.transform.position right backGO.transform.position back frontGO.transform.position front list.Clear() list.Add(center) list.Add(left) list.Add(right) list.Add(front) list.Add(back) void DrawDebugRays() for (int i 0 i lt list.Count i ) Color color Color.red switch (i) case 0 color Color.green break case 1 case 2 color Color.blue break Debug.DrawRay(Vector3.zero, (Vector3)list i , color)


Unity 4 mecanim 'Quaternion to Matrix conversion failed, input quaternion is invalid' I'm trying to animate a stick figure in Unity, with placeholder animations. Character is built animated in Blender, exported to FBX. When imported to Unity, everything appears correct in the editor. All animations are imported, and i can preview them normally. I set up the "rig" section of the model import to use generic rigging. This creates the avatar which is used in mecanim. I set up a simple "walkForward" animation, and setup mecanim parameters to get it called when the player moved forward all that works. The animation is called at the right times. However, during play, as soon as any animation is started on the avatar, the model disappears, and a flood of error messages appear in the console, stating Quaternion to Matrix conversion failed because input Quaternion is invalid 1. IND00, 1. IND00, 1. IND00, 1. IND00 1 IND00 I'm not altering the animation with any scripts of my own, it's all mecanim. Is there a setting i'm missing? I'm using Unity 4.3.0.0f4, building exporting my mesh with Blender (latest).


Is Unreal engine or Unity better for high graphics low file size mobile games? My objective of learning game development is to make a 3d relatively high graphics mobile game but that should be in 150 mb. I don't know should I start with unity or unreal engine. I found that people say unreal engine is better for 3d games and unity is better for mobile game development. As I have no experience, can anyone suggest me an engine with some reasons?


Unity Editor stops updating ScriptableObjects if I click away from them in editor I'm trying to be better about structuring my code, and I think I'm doing it right. The issue I've got right now is I need to get joystick inputs, scale those values appropriately, and then use that scaled data on any number of MonoBehaviour scripts. I'm trying to split the input conditioning from the end user, and I'd like to do that by using a ScriptableObject to hold the conditioned data. I was thinking that a MonoBehaviour script would run, get the joystick data, scale it, and then push that data to variables in the ScaledJoystickData ScriptableObject. Later, a second MonoBehaviour script would access the variables in the ScaledJoystickData and use those to move the things in the game. I'm understanding the benefits of structuring the code this way, especially in that I can access the ScriptableObject from the editor and manipulate those values I don't actually need to have a joystick connected, and I'm free to test either end of the input handling independently. The problem is that, if I am looking at the ScriptableObject instance in the editor, it stops updating as soon as I click away from it (to the consuming GameObject). If I click back to the ScriptableObejct instance, none of the values update. Nothing on the GameObject's script updates unless I start the game with that GO selected in editor, and again THAT fails to update if I click off and click back. The GameObject script is currently using the values from the ScriptableObject instance and piping them to public variables, and the public variables aren't updating. Is there some bug with ScriptableObjects, or am I doing this wrong? EDIT Here's an example. Make a script called "ExampleSO" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine CreateAssetMenu public class ExampleSO ScriptableObject public float stashedVar 0f Make a script called "ExampleWriter" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleWriter MonoBehaviour public float scaling 2f public float scaledInput 0f public ExampleSO exampleSO null Update is called once per frame void Update() if(exampleSO! null) scaledInput scaling (Input.GetKey(KeyCode.LeftArrow) ? 1f 0f) exampleSO.stashedVar scaledInput Make a script called "ExampleReader" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleReader MonoBehaviour public float display 0f public ExampleSO exampleSO null void Update() if(exampleSO! null) display exampleSO.stashedVar Create an instance of the ExampleSO, add the ExampleWriter to a game object, and put the ExampleSO instance into the ExampleWriter slot. Highlight the game object holding ExampleWriter and run it. Push the left arrow key and see the value toggle 0 2. Click the ExampleSO instance. Nothing is happening there now. Click back on the game object, and now it doesn't update either. If you have the ExampleReader on the same game object then it won't work at all. ExampleReader will read fine, if you have it on a separate GameObject, but again if you click off and click back then it stops responding.


GetComponentsInChildren() raises error I have a gameobject to which a script is attached. In this script I have the following code foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) BagItem nBagItemScript g.GetComponent lt BagItem gt () if (nBagItemScript ! null) Bounds nBounds Helpers.BoundsFromGO(g) Vector3 nPos new Vector3((nBounds.size.x 2) nBounds.center.x, mapHeight (nBounds.size.y 2) nBounds.center.y, 0.01f) g.transform.localPosition nPos I thought this code was fail safe, but Unity outputs the following error message ArgumentException GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface. UnityEngine.GameObject.GetComponentsInChildren GameObject (Boolean includeInactive) (at C buildslave unity build Runtime Export GameObject.bindings.cs 133) UnityEngine.Component.GetComponentsInChildren GameObject (Boolean includeInactive) (at C buildslave unity build Runtime Export Component.bindings.cs 88) UnityEngine.Component.GetComponentsInChildren GameObject () (at C buildslave unity build Runtime Export Component.bindings.cs 98) Bag.pUpdatePositions () (at Assets Bag.cs 173) Bag.Update () (at Assets Bag.cs 107) Can somebody tell me which error Unity C is choking on here? Is the error really in this line foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) ... or perhaps somewhere else? Thank you very much!


Keeping an object constrained to a 2d radius based off of the camera A few weeks back I posted a question about keeping an object on the screen. What I would like to do now is clamping an object around a 2d radius based on the camera. I'm need this for a reticule for this on rail shooter I've been making. (like that of starfox) Here is the current code I am using Vector3 movementx transform.TransformDirection(Vector3.right Input.GetAxis("Mouse X") aimSpeed) Vector3 newPosx transform.position movementx Vector3 offsetx newPosx centerPt.position transform.position centerPt.position Vector3.ClampMagnitude(offsetx, radius) the same for the y axis The problem with this set up is that I'm restricting it around 3 dimensional objects base off their locations in the world. (this is restricting the players movement towards the edges not letting the player to move the reticule to the side) So this is what I've tried Vector3 screenPosition Camera.main.WorldToScreenPoint(transform.position) Vector3 shipOnScreen Camera.main.WorldToScreenPoint(Ship.position) Vector3 movementx transform.TransformDirection(Vector3.right Input.GetAxis("Mouse X") aimSpeed) Vector3 newPosx screenPosition movementx Vector3 offsetx newPosx shipOnScreen transform.position shipOnScreen Vector3.ClampMagnitude(offsetx, radius) the same for the y axis This just seems to send the empty (which the ship is pointing at) off some where else in the world I cant even tell if I'm moving it or if its just moving with the parent object. (I've tried different variations with this moving the screenPosition swapping it with the transforms position in world space to no avail) My guess is that its not converting 2d space to 3d space when I try to clamp a 3d object within that radius. I would like to keep my reticule at an empty point on the screen and not replace it with the cursor. Edit Okay i have now thought up a new system that still needs some work. Having an empty object next to the reticule. With this I cut out the need for a 2d radius but I need this object object follow the ship on on the screen with taking in account the perception of the camera. I have taken a measure of the height and width of the camera. Its not too exact but it should do. So i guess I would like to know how the coordinate system on the camera is set up. like where is (0, 0) update Okay I've found a way to do this but it took a quite a bit of math on my part and a bit of estimation on my behalf. The way I've set it up is that I moving the pivot the same way I'm moving the ship only I'm multiplying it times the proportion of distance the ship can move side to side vs the distance the pivot can move side to side. I still have not built in an equation that will allow me to move the point farther back with more accuracy but this is a good temporary fix and if i really have to move it I'll i do the math again. but I would still like to have the equation of the rate of change. I'm not that brilliant at related rates. If you want to see my math I noted it down. but if i can have an equation out of this it would work perfectly while changing ship distance (constant) (61.6209, 27.5131) first measure distance 100 point A distance (320.5, 143.1) 5.20115872075484 y multiplier 5.200473802917458 x multiplier so the multiplier at 100 5.2 distance 50 point B distance (192.0436, 85.74551) 3.11633 y multiplier 3.11633 x multiplier so the multiplier at 100 3.11633 Rate of change (5.2 3.1165) (100 50) ROC ROC 0.04166934 mt 0.042 y No idea x distances from ship 0.042 Oh in case your wondering how i got my measurements I measured the distance manually with points.