Hello Unity answers community, today I present you with the opportunity to help another newbie like myself access a float variable from one C# script in another C# script. I’ve spent countless hours researching the gameObject.GetComponent methods, and have seen a plethora of examples provided here on the answers forums and elsewhere on the web. Yet for some reason unbeknownst to me, even after numerous tweaks to both of my two scripts, I still can’t manage to get the game running. The title above describes the error I am currently receiving.
Anyway, here is the logic behind my two scripts. The first script, seen below, is a simple countdown timer script that uses the public float variable “timeLeft” to countdown from a set value; this one functions as it should. The second script I created was intended to be one that was activated on trigger enter. The script could be placed and used universally on numerous triggers, these object triggers would either add or subtract time based upon their significance in the game, then the object would destruct itself in order to prevent exploits.
Here are my two scripts:
Timer.cs
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public float timeLeft = 15.0f;
public void Update() {
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f) {
Application.LoadLevel(1);
}
}
public void OnGUI() {
GUI.Box(new Rect(600, 10, 100, 20), "Time Left: " + (int)timeLeft);
}
}
ModifyTimer.cs
using UnityEngine;
using System.Collections;
public class ModifyTimer : MonoBehaviour {
public GameObject Timer;
public timeLeft TimerScript;
public float addTime = 0f;
public float subTime = 0f;
void Awake () {
//Reference the timeLeft variable in the Timer script
Timer = GameObject.FindGameObjectWithTag(Tags.timer);
TimerScript = Timer.GetComponent<timeLeft>();
}
void OnTriggerEnter (Collider other) {
//Either add or subtract time to timeLeft based on variable input
if (addTime >= 1) {
Timer.timeLeft += addTime;
}
if (subTime >= 1) {
Timer.timeLeft -= subTime;
}
Destroy(gameObject);
}
}
So why can’t the timeLeft variable be modified in this way? I have tried so many different methods of accessing the timeLeft variable from the first script to no avail. Any help is greatly appreciated, please go easy on me as I just recently started working in Unity with C# as a student.