- Home /
Referencing other scripts: -5 seconds rule on timer
Hello Unity Users, I need help with my game timer. In my game, when the ball hits the finishline trigger, what is suppose to happen is:
The ball is destroyed
minus 5 seconds from the Count-Up timer
I dont know why its giving me problems. I am referring The timer from my working timer script into my finishline script. I keep getting this error.
Assets/Scripts/Finishline.cs(30,32): error CS0120: An object reference is required to access non-static member `Clock2.OnGUI()'
Please Help! Novice Unity User
public class Finishline : MonoBehaviour
{
//declare scoring variables
public int count;
public GUIText countText;
//Script Reference
public int Clock2.OnGUI.Dseconds;
public Clock2 Timer;
void Start ()
{
count = 0;
SetCountText();
}
//if the balls collides with a finishline collider, finishline destroys the balls and add a point to score.
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Ball")
{
Debug.Log ("Object Entered the trigger");
count += 1;
// subtract 5 seconds whenever a ball enters the finishline
Clock2.OnGUI().Dseconds = -5;
SetCountText ();
//gameObject.SetActive(false);
Destroy (other.gameObject);
}
if (count > 12)
{
Time.timeScale = 0;
}
}
void SetCountText()
{
countText.text = "Number of Balls Collected: "+ count.ToString();
//if(count>11)
// {
// winText.text = "You Win!";
// }
}
}
Answer by fafase · Jul 27, 2014 at 07:38 PM
Clock2.OnGUI().Dseconds = -5;
Here something is wrong. You cannot (or at least should not) use a method with a name already used by Unity.
I don't quite get what you are after since you want to call the method and then a sub variable which cannot be done in this case.
OnGUI is already taken care by Unity engine so you are not supposed to call yourself, you might as well create a new method with new naming.
Finally I think you are after a common case which is accessing variables from other scripts. You could read the link below I think you will find what you are after.
The Dseconds that I am trying to change is within the OnGUI() in my Clock2 script. I looked at the website and I am not sure how else I can get to this local variable Dseconds. How could I rename OnGUI?
The variable is in the script, I would think it is not declared inside the method as it would not make sense.
Then you can use the GetComponent method.
Thanks fafase for helping me out. You are right that I need to use GetComponent method but I am trying to reference a variable. From Statement response from another page, I need to refer to the variable through a gameObject then use the GetComponent method.
http://answers.unity3d.com/questions/42843/referencing-non-static-variables-from-another-scri.html