- Home /
Duplicate Question
How to access other scripts from one script
I am trying to write code to move other GameObjects in a scene to a new location when a specific GameObject is clicked with the mouse. Right now I have the following test code:
void Update () {
if(Input.GetMouseButtonDown(0)){
Move m = GetComponent<Move>();
m.doSomething();
}
Move is a separate script that contains the method:
public void doSomething () {
transform.position = new Vector3(0, 0, 0);
}
When I run this, I get the "NullReferenceException: Object reference not set to an instance of an object" error. Any ideas why?
Edit: I forgot to mention that Move is attached to a different object. When I click on an object with the first script attached, I want the object with the Move script to move.
Is your script called $$anonymous$$ove attached to the same object?
Theres your issue. calling GetComponent on its own will get a component from the object that script is attached to. You will need to be like 'otherObject.getComponent()' to get the $$anonymous$$ove script from the other object :)
Ah, I see. But how do I reference the other object? I can't say Cube2.getComponent(), can I?
There are lots of ways to get that other object. You could declare a public variable at the start of your script like
public Transform otherObject;
Drag the other object into it in the editor and then call
$$anonymous$$ove m = otherObject.getComponent<$$anonymous$$ove>();
This only works if you can point to that object specifically though.
You could various find like GameObject.Find or FindObjectsWithTag to get it. These are a lot more costly operations than the first, so use these during the Start method so its only once and save that reference to $$anonymous$$ove m.
Also, you can have lots of scripts on any object, maybe you could attach your script to the same object as the one $$anonymous$$ove is on?
Theses are just some examples. Id need more context if you want some more specific advice, hopefully you can take it from here though :D
Follow this Question
Related Questions
troubleshooting NullReferenceException 2 Answers
NullReferenceException 2 Answers
Material[] Object reference not set when instantiating 2 Answers