How to set float, bool from one script to the other?
I know how to make reference from another script and how to use it's functions but I am trying to set a bool using the script I made reference to. The script that contains those variables is the other one and the bool and / or floats should change there too, but it isn't. Is it suppose to work this way? is there a way to change on both?
__________________________________________OriginalScript_________________________________________
void Update () {
if (DoesItEvenWork == true) {
Debug.Log ("It works!");
}
__________________________________________OriginalScript_________________________________________
__________________________________________Reference Script______________________________________
if (Input.GetKey ("e")) {
ScriptReference.DoesItEvenWork = true;
}
__________________________________________Reference Script______________________________________
Sorry but your code-sample here is all over the place... We dont know in witch script the variable DoesItEvenWork is declared... so yeah. Please use actual code samples next time.
If you want to change the variable of another script you will have to make the variable public. But it seems like you have already done that correctly. Is your OriginalScript attached to an active gameobject? Update in only called on active objects. Also try debugging DoesItEvenWork in ReferenceScript so you see if the value has actually changed.
All my variables are public and all gameobjects are active. So this did not helped much.
Answer by Guhanesh · Mar 17, 2016 at 06:34 AM
using UnityEngine;
using System.Collections;
public class OriginalScript : MonoBehaviour {
public bool DoesItEvenWork=false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (DoesItEvenWork == true) {
Debug.Log ("It works!");
}
}
}
Attach the above script to a gameobject and rename the gameobject to GameObject.
using UnityEngine;
using System.Collections;
public class referenceScript : MonoBehaviour {
OriginalScript orignalSctipt;
// Use this for initialization
void Start () {
orignalSctipt=GameObject.Find("GameObject").GetComponent<OriginalScript>();
}
// Update is called once per frame
void Update () {
if (Input.GetKey ("e")) {
orignalSctipt.DoesItEvenWork=true;
}
}
}
Attach the above script to another gameobject in the scene.And play and check.
in referenceScript, line 8 should be:
originalScript = (OriginalScript ) FindObjectOfType(typeof(OriginalScript));
or the object has to be named "GameObject" (and being the first one, else GetComponent will result null)