- Home /
How to get float value from other script?
Hi, (Sorry for my bad English) I wrote script that change item which I'm holding:
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
ItemInHand = 1;
Item1.SetActive(true);
Item2.SetActive(false);
}
}
And another script:
void OnTriggerStay(Collider other)
{
if (other.tag == "Player")
{
text.enabled = true;
intree = true;
Debug.Log("In trigger.");
if (Input.GetKeyDown(KeyCode.E) & ###ItemInHand = 1###)
{
text.enabled = false;
Invoke("one", 0.3f);
}
}
}
How to get ItemInHand value in second script?
Answer by Reynarz · Aug 05, 2017 at 02:18 PM
There are some cases:
case 1: your classes are in the same object.
public class MyClass1 : MonoBehaviour
{
public float _itemInHand = 0; //public field
}
public MyClass2 : MonoBehaviour
{
private void Start()
{
var class1 = GetComponent<MyClass1>();
class1._itemInHand = 3;
}
}
Case 2: your classes are in diferents objects
public class MyClass1 : MonoBehaviour
{
public float _itemInHand = 0; //public field
}
public MyClass2 : MonoBehaviour
{
private void Start()
{
var class1 = GameObject.Find("MyObject").GetComponent<MyClass1>();
class1._itemInHand = 3;
}
}
Answer by WilliamBurbidge · Aug 05, 2017 at 01:58 PM
What i did was a seperate class which was a "public static class " which kept all my variables to use in more than one script. Then to access that variable you do the name of the class then "." with the variable name. For example myclass.variable . Hope that helps.
$$anonymous$$an noo, that is a bad bad practice. when you do that you are building a bad design, why is this? because you say, "i wanna set my variable with global access". what happen if you make an enemy with static properties?. if you hit an enemy, all enemies will be hitted too :/ that is just an problem of many, but you will get some problems more complex out there if you mess with the static keyword so much.
Your answer
Follow this Question
Related Questions
zero is not zero 2 Answers
Have a problems with a values 1 Answer
Instantiating a prefab and values 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers