i have a script to move a parent of the object one way, i want the other to come in another way. My problem is i cant seem to set and use a global variable. i dont want it static because i want to be able to use it to bring a item in as one is going out, and then be able to go back.
Script one
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public Vector3 EndLocation;
public float SpeedMuilt;
public bool click = false;
// Use this for initialization
void OnMouseDown () {
click = true;
}
void Update () {
if (click == true) {
transform.parent.Translate(EndLocation *Time.deltaTime * SpeedMuilt );
}
}
}
now i want a script to check if it was clicked and move in. the problem is click is in the other script and i need a to access the variable in the new script
this is on the incomeing objcet
using UnityEngine;
using System.Collections;
public class Follow : MonoBehaviour {
public Vector3 EndLocation;
public float SpeedMuilt;
void Update () {
if (click == true) {
transform.parent.Translate(EndLocation *Time.deltaTime * SpeedMuilt );
}
}
}
FIRST: You’ll have to get the component from a gameobject by using GameObject.GetComponent(typeof(YouComponentHere));
SECOND: If your component is on another gameobject you’ll have to use GameObject.Find("NameHere") but if the component is on the same gameobject just use this.GameObject.GetComponent
THIRD: In C# you most cast the game object correctly to do that you’ll do like this: ((YourComponentHere)GameObject.GetComponent(typeof(YouComponentHere))).YourvariableNameHere = Something;
FOURTH: Profit???
this.GameObject.GetComponent is wrong, should be
gameObject.GetComponent but GetComponent on its own is sufficient.
If your component is on another gameobject you’ll have to use GameObject.Find(“NameHere”) is also wrong, you can use all kinds of ways to get a reference to another GameObject, like FindGameObjectWithTag, a public variable in which you drop the GameObject via inspector.
True indeed however I did have some problems in a version further back where the generic typing didn’t work very well, but since it probably works fine now i’ll take note of that ^^
Again correct, I didn’t have any project loaded so wasn’t able to remember the casing in my head but close enough.