Access an object reference variable from parent class
Several scripts need to access the rigidbody on my two playerShip gameObjects. Re-typing GetComponent for each script I write is getting tedious, so I created a helper class called "Element" that stores references to frequently referenced objects in the scene.
public class Element : MonoBehaviour {
public GameObject leftShip;
public GameObject rightShip;
protected Rigidbody leftRigid;
protected Rigidbody rightRigid;
void Start () {
leftRigid = leftShip.GetComponent<Rigidbody>();
rightRigid = rightShip.GetComponent<Rigidbody>();
}
}
I then have a child class called "PlayerInput" which applies forces to the rigidbodies of the ship.
public class ShipInput : Element {
private void MoveShip (Vector2 speedAxis) {
leftRigid.AddForce (Vector3.right * leftShipForce * thrust * 100f);
rightRigid.AddForce (Vector3.right * rightShipForce * thrust * 100f);
}
}
}
When I play the game, I'm getting a null reference error for left rigid and right rigid variables any time the function "MoveShip" is called. Note that the two player ship gameObjects were dragged into the element class from the scene (not a prefab) and that the element class is attached to a gameObject in the scene called "LevelManager."
Is this the correct way to do this? If not, how could I store references to commonly used objects in a similar way? Thanks for reading.
Are the variables being referenced before/during the Start function? Is that the full ShipInput script?
I fixed it but you were on the the right track. Turns out for some reason that child never had access to it's paren'ts start function. If you read my reply below you can see what I did to solve the problem. Thanks!
Answer by tylersbrown01 · May 21, 2016 at 08:08 PM
I figured it out!! So what happened is the child class didn't have access to the parent's start function. So I changed the start function in the parent class to "Protected void GetComponents ()" and then called GetComponents() in the child script's start () function.
EDIT: This is actually not the best option as it is taxing and redundant for each child class to have to call the GetComponents() methods in it's awake function.
The best solution is to simply change Start() to Awake() in the parent class
Thank you! I know this question is old, but I had to sign in and thank you for the propper answer. I couldn't find a hint to this issue anywhere and just never knew that childs can't access their parents start. I guess I am not the only one so hopefully more people will see it this way!