- Home /
NullReferenceException?
So I am trying to do something and I assume I am making a very simple mistake. this code doesn't work:
Rigidbody clone;
CivMoveSpeed = (Random.Range(0,1) - 0.5f) * Random.Range(4,8) * 100f;
clone = Instantiate(Civ, CivSpawn, transform.rotation) as Rigidbody;
clone.velocity = transform.forward * CivMoveSpeed;
but this does:
Rigidbody clone;
CivMoveSpeed = (Random.Range(0,1) - 0.5f) * Random.Range(4,8) * 100f;
clone = Instantiate(Civ, CivSpawn, transform.rotation) as Rigidbody;
//clone.velocity = transform.forward * CivMoveSpeed;
I am not sure where the problem is. I have an almost identical code in another file that works fine. it is saying that the error is coming from commented out line of code. I also tried leaving just the transform and that didn't work so I tried an entirely new vector which didn't work either. Any ideas?
Answer by Eric5h5 · Dec 21, 2012 at 07:44 AM
Presumably your "Civ" variable is not a Rigidbody, so "clone" is null. (By the way, your code would be more readable if you stick to the standard Unity convention of using lowercase for variables while keeping uppercase for methods and classes.)
You were correct. I declared Civ as a gameobject for some reason. I will be sure to keep the variable convention in $$anonymous$$d in the future.
Your answer
![](https://koobas.hobune.stream/wayback/20220613085738im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Code works in Editor but not in standalone 1 Answer
Null variable 2 Answers
iTween NullReferenceException error 1 Answer
nullrefernceexception 0 Answers