How to connect two c# scripts and connect varibles?
I have attempted to connect a variable from one c# to another and I can't figure out were I have gone wrong. The premise of my game is to get to a checkpoint before the timer runs out and when you have hit said checkpoint the timer resets, can someone please help? Here is my code;
using UnityEngine;
using System.Collections;
public class onTrigger : MonoBehaviour {
void OnTriggerExit(Collider other)
{
GetComponent<Timer>().m_Time = 5f;
}
/*
IEnumerator Wait()
{
yield return new WaitForSeconds(1);
}
*/
}
public class Timer : MonoBehaviour
{
public Slider m_Slider;
public float m_Time;
public float m_StartTime = 5f;
}
I am trying to share the variable m_Time. Thank you
You should tell us why you think you have gone wrong. Do you get an error? Or doesn't the value just change? Those scripts don't have anything wrong with them as such I believe.
Answer by KazYamof · May 20, 2016 at 07:13 PM
I will assume you are not using any design pattern like Factory, Singleton, etc. and are no worried about everything be public on your class. So just to demonstrate, you can do something like this:
public class TriggerManager : MonoBehaviour { //avoid onTrigger as class name, sounds like a Event name
public Timer myTimer; //field of the class Timer
void Awake()
{
this.myTimer = Find("TimerGameObjectNameHere").GetComponent<Timer>(); //try to find the object
if (this.myTimer == null) //null check, if there is not a Timer instantiated, create one and assign the reference to the local field
this.myTimer = new GameObject("TimerGameObjectNameHere").AddComponent<Timer>();
}
void OnTriggerExit(Collider other)
{
this.myTimer.m_Time = 5f;
}
}
//still the same as yours
public class Timer : MonoBehaviour
{
public Slider m_Slider;
public float m_Time;
public float m_StartTime = 5f;
}
Never $$anonymous$$d, I forget to assign a object, thank you very much for your help.
Your answer
Follow this Question
Related Questions
assign a new value to a variable 0 Answers
Script error and no Variables showing 0 Answers
How to compare two different variables in two different scripts? 0 Answers
How can I access to child objects variables from other C# script ? 0 Answers
Invoking a Function From A Variblized Script And Object 1 Answer