I understand what a null reference is for the most part, but I have no idea why I am getting one here. I simply instantiate a projectile, and it says:
NullReferenceException: Object reference not set to an instance of an object
Im lost - I thought I was giving it a reference by saying myArrow = Instantiate…
How do I give this object a reference?
[RPC]
void SpawnProjectile (Vector3 position, Quaternion rotation, string originatorName, string team)
{
GameObject myArrow;
myArrow = Instantiate(arrow, position, rotation) as GameObject;
//THE BELOW LINE IS APPARENTLY WHAT IS CAUSING THE ERROR ACCORDING TO MONODEVELOP
myArrow.rigidbody.AddRelativeForce(Vector3.forward * 1000);
//Access the Arrow script on instantiated arrow and supply players name and team.
Arrow bScript = myArrow.GetComponent<Arrow>();
bScript.myOriginator = originatorName;
bScript.team = team;
//bScript.arrowPower = power;
}
}
Try this:
[RPC]
void SpawnProjectile (Vector3 position, Quaternion rotation, string originatorName, string team)
{
GameObject myArrow;
myArrow = Instantiate(arrow, position, rotation) as GameObject;
//THE BELOW LINE IS APPARENTLY WHAT IS CAUSING THE ERROR ACCORDING TO MONODEVELOP
Rigidbody rb = (Rigidbody)myArrow.GetComponent("Rigidbody");
if( rb == null)
{
rb = (Rigidbody)myArrow.AddComponent("Rigidbody");
}
rb.AddRelativeForce(Vector3.forward * 1000);
//Access the Arrow script on instantiated arrow and supply players name and team.
Arrow bScript = myArrow.GetComponent<Arrow>();
bScript.myOriginator = originatorName;
bScript.team = team;
//bScript.arrowPower = power;
}
}
GameObjects don’t have rigidbodies by default. You have to explicitly add them.
Well at this point I have been able to get rid of the null reference by setting my arrow to instantiate as a transform. IE:
Transform myArrow = Instantiate(arrow, position, rotation) as Transform;
Unfortunately the arrows raycasts are not registering hits on the enemy player - although they are obviously hitting the other player on both player’s screens. Since its a seperate issue though I am going to go ahead and mark this as answered I guess. if anyone has any input on why setting as a transform fixed the null reference I would love to understand more about that. Otherwise I will just assume its because the variable arrow is declared as a transform so that was causing issues maybe.
Thanks again everyone for their help on this.