Hey guys, how can I access a variable from another Script inside IF ?
I accessed a float variable on another script, and changed it, but I want to limit the value on this script, this is my script:
if (Input.GetKey(KeyCode.D) && apertou == true)
{
float water = GameObject.FindWithTag("Boia").GetComponent<Floater>().waterLevel += Time.deltaTime;
if (Input.GetKey(KeyCode.D) && apertou == true)
{
float water = GameObject.FindWithTag("Boia").GetComponent<Floater>().waterLevel += Time.deltaTime;
}
if ( water >= 6806 (or the right code to limit the variable waterLevel))
{
Debug.Log("go");
}
Hi,
Its not actually possible to access a variable that is created under a function
Because Unity only checks the variables that are created outside a function
Eg
1 Using Variables outside the function(void , if , else …etc)
Add both the script to the same objectRight Working Method
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public float x= 0;
public float y = 0;
void Update(){
if(Input.GetKeyDown(KeyCode.A)){
x++;//same as x+=1 ie adds 1 to the current number
}
if(Input.GetKeyDown(KeyCode.B)){
y++;
}
}
}
Getting value from other script an printing it
using UnityEngine;
using System.Collections;
public class ValueObtainer : MonoBehaviour {
void Update(){
float xvalue = transform.GetComponent(Test).x;
print(x);//or y your wish
}
}
now the same script with x and y variables inside the function
Wrong method ,doesnot work
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Update(){
if(Input.GetKeyDown(KeyCode.A)){
flaot x+=1;//same as x+=1 ie adds 1 to the current number
}
if(Input.GetKeyDown(KeyCode.B)){
float y+=1;
}
}
}
Getting value from other script an printing it
using UnityEngine;
using System.Collections;
public class ValueObtainer : MonoBehaviour {
void Update(){
float xvalue = transform.GetComponent(Test).x;
print(x);//or y your wish
}
}
Here,since x and y values are inside a function,in this case "void and if"functions
Unity returns value null