Duplicate/SUPER COMMON Question
Access another object's variable
I'm trying to access a specific variable in a script attached to another gameobject. I have no idea how to do this. Does anyone else know? using UnityEngine; using System.Collections;
public class StandardAttacksP1 : MonoBehaviour {
public GameObject controllerDetect;
public Component controllers;
void Start () {
controllers = controllerDetect.GetComponentInChildren<ControllerAmountDet> ();
}
void Update () {
if (controllers.playerOneKeyboard == true) {
//Do something
}
}
}
Do you get an error with this script? You are looking for a script in a child of the object holding this script correct? The child needs to be active for this to work
The problem was that controllers.playerOne$$anonymous$$eyboard == true couldn't be used, and yes, it is in a child.
This is a super common question and the answers are so rife that its amazing it they dont jump out at you.
In future, please conduct searches for existing material before posting a question which is actually answered in the manual.
http://docs.unity3d.com/410/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
Answer by JigneshKoradiya · Apr 09, 2016 at 07:30 AM
GameObject.Find("objectname").GetComponent().varibalename = 2;
make sure that variable are public
Thanks. This worked wonderfully. All I needed to change was the = 2 part.
Follow this Question
Related Questions
How to get scripts to detect foreign variable change? 0 Answers
destory object not variable 2 Answers
Novice Question: Assigning GameObject properties efficiently. 1 Answer
How to get access to variable from another script without knowing script's name c# 2 Answers
storing velocity and temporarly using it 0 Answers