Let’s say I have 3 STATIC floats in ONE script that are constantly changing.
How can I create a variable in ANOTHER script (which is attached to many prefabs), that is always equal to one of the floats of the first script?
What I want to avoid is using long if, else if statements such as:
if (I am Object1)
theFloat = otherScript.variable1;
else if (I am Object2)
theFloat = otherScript.variable2;
else if (I am Object3)
theFloat = otherScript.variable3;
using UnityEngine;
using System.Collections;
public class SomeScript: MonoBehaviour {
public float myFloat = 0.0f;
public float myFloat1 = 0.0f;
public float myFloat2 = 0.0f;
public float myFloat3 = 0.0f;
public float myFloat4 = 0.0f;
}
using UnityEngine;
using System.Collections;
public class AnotherScript: MonoBehaviour {
private SomeScript sS;
void Start()
{
sS = WhateverObjectItsOn.GetComponent<SomeScript>();
}
void Update()
{
Debug.Log(sS.myFloat + " " + sS.myFloat1 + " " + sS.myFloat2 + " ");
}
}
What you do is reference the script with GetComponent. You can then refer to the variable with the dot operator as use it as if it were in this script. It stays up to date this way.
You can use C# properties for this. Say this is your class with the static floats :
public class StaticFloats
{
public static float float1;
public static float float2;
public static float float3;
}
You can then access them from another class with a property like so:
public class ThingThatReferencesFloats
{
public float Float1
{
get
{
return StaticFloats.float1;
}
}
// Repeat for Float2 and Float3
// When you want to access the value in a function such as update, simply do the following:
void Update()
{
float someValue = Float1;
}
}
Each time you “get” Float1, it will retrieve it from the script containing the static floats. If you wish to also be able to set the static float from elsewhere, you can add set accessor to the property too.