- Home /
What am I doing wrong when disabling a script?
Here is my code, i simply want to disable a script upon startup but I'm having serious issues with it. I've been following another post http://answers.unity3d.com/questions/548362/enabledisable-script-from-another-script-c.html
I'm following it step by step but still seem to be having trouble :/
Here is the code:
public moveTowardsPlayer movement;
void Start()
{
movement = GetComponent<moveTowardsPlayer>();
movement.enabled = false;
}
I just want to disable the moveTowardsPlayer script when the scene begins but I get this error: Object reference not set to an instance of an object
Can anyone shed some light for me?
Likely your GetComponent() is failing to find the 'moveTowardsPlayer' component. Is the 'moveTowardsPlayer' script attached to the same game object as this script? Any change this script is attached to more than one game object, and one of those does not have a 'moveTowardsPlayer' script?
The moveTowardsPlayer script is not on the same object as this no. I have a few objects in the scene and the moveTowardsPlayer script is attached to 4 of them. That must be it so? How would i make reference to them?
Solution is to check whether you are running the script on the same object which has moveTowardsPlayer
component.
If its not, try to attach the script on that object.
Answer by Joxno · Aug 17, 2014 at 04:53 PM
The problem here is that your moveTowardsPlayer script MUST be present on the same game object that this script is attached to due to the reason that GetComponent retrieves a component from 'this' gameObject.
If GetComponent does not find a script it returns null, therefore when you do movement.enabled = false; movement does not have a reference therefore giving you the object reference error.
The solution to this is to first retrieve the gameObject that moveTowardsPlayer is present on, and then disable the script.
movement = GameObject.Find("Player").GetComponent<moveTowardsPlayer>();
movement.enabled = false;
Ah I see now, I thought it just disabled the script as if it were a global event. Thanks for the input Joxno