-1

In the following line of code, _pro is another class's instance that has a Transform called Target and posi is a Vector3 as well and has a valid value.

_pro.Target.transform.position = new Vector3(posi.x, posi.y, posi.z);

I want to assign the value of posi to Target.transform.position but it throws a NullReferenceException.

After inspecting each part, _pro is null. Here is how I tried to instantiate _pro:

public projectile _pro;
GameObject go = GameObject.Find("enemy");    // go is not null
_pro = go.GetComponent<projectile>();        // _pro is null
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
systemdebt
  • 4,589
  • 10
  • 55
  • 116
  • 1
    Either `_pro`, `Target` or `transform` is null. Have a look in the debugger. – Chris Jul 27 '14 at 19:32
  • @cHRIS: _pro is null. I am editing the above code, please have a look and let me know why is _pro null. Thanks – systemdebt Jul 27 '14 at 19:37
  • I am facing problem in instantiating it properly, would be great if someone here could help me. – systemdebt Jul 27 '14 at 19:41
  • 1
    From the docs: `Returns the component with name type if the game object has one attached, null if it doesn't.` – Chris Jul 27 '14 at 19:41
  • I checked it and _pro is definitely null and is not assigned a value but I am unable to understand why is it so? – systemdebt Jul 27 '14 at 19:43
  • 2
    Well the null in this case means that the enemy game object doesn't have a projectile attached - so begin with figuring out why that is. – Chris Jul 27 '14 at 19:45
  • Where are you creating the projectile and attaching it to the "enemy"? – LVBen Jul 27 '14 at 20:12

1 Answers1

1

The "enemy" game object that was found does not have a projectile component attached to it, so that is why go.GetComponent<projectile>() is giving you null.

You need to instantiate the projectile somewhere in your code. You can do something like this:

go.AddComponent<projectile>(); // where go is the "enemy" game object

or this:

var pro = CreateInstance<projectile>();
pro.transform.parent = go.transform.parent; // go is the "enemy" game object
LVBen
  • 2,041
  • 13
  • 27