-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
  • 63,310
  • 12
  • 110
  • 157
systemdebt
  • 3,755
  • 10
  • 45
  • 103

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,002
  • 12
  • 27