- Home /
On trigger and button input to enable/disable script
hello everyone, im tryin to make a script to attach on a gameobject that will find my player via tag and enable/disable the third person controller script on key press, i went on to do this by using nested ifs and it works but when i press the buttons i get null reference please help me!:
var scriptname : ThirdPersonController;
var Player : GameObject;
function Start () {
scriptname.enabled = false;
}
function OnTriggerStay (other : Collider)
{
if(other.gameObject.tag == "Player"){
if(Input.GetKeyDown("2")) {
scriptname.GetComponent(ThirdPersonController).enabled = true;
}
}
else if(Input.GetKeyDown("3")) {
scriptname.GetComponent(ThirdPersonController).enabled = false;
}
}
Answer by Dave-Carlile · Feb 08, 2013 at 04:22 PM
What is your scriptname
variable set to? Do you even need that? Seems like scriptname
should either be a string, set to the name of the script component you want to find and call it like this:
GetComponent(scriptname).enabled = true;
or just remove scriptname
altogether if you're always looking for the ThirdPersonController
component.
GetComponent(ThirdPersonController).enabled = true;
i removed scriptname all together but its still giving me null reference when i press the buttons
Answer by Kergal · Feb 08, 2013 at 04:43 PM
change line 13 and 18 - I am sure you meant Player.GetComponent... etc.
even though it is more economical to store the access to the script in a variable... - but you clearly do not understand the concept of storing something in a variable yet ;)
Make sure you understand what an object is ..and what a component is and how you would access component X on GameObject Y . That is very important (and very basic stuff) .
like Dave mentioned - you did not set your (poorly named) variable scriptname to anything. (and if you didn't do drag and drop .. you also didn't set your player to anything).
thanks for the answer im only a 3 days old "programmer" so i know im not familiar with most of the basic stuff yet, changing to Player.GetComponent got rid of the null reff but it doesnt do anything now when i press them
Your answer
![](https://koobas.hobune.stream/wayback/20220613092345im_/https://answers.unity.com/themes/thub/images/avi.jpg)