- Home /
Is an object with an update function possible? (C#)
If I have a class, and In another script, I create an instance of that class, is the update function usable?
Nothing I put in it seems to run.
The class:
using UnityEngine;
using System.Collections;
public class MM_Timer {
float delayy;
float time;
public bool tik = false;
bool randmode;
float min;
float max;
bool paused = false;
void Update () {
if (time < delayy && tik == false && paused == false)
{
time += Time.deltaTime;
}
else if (!paused)
{
tik = true;
if(randmode){
delayy = Random.Range(min, max);
}
}
}
public bool tick(){
if (tik){
tik = false;
return true;
}
else{return false;}
}
public void start(){paused = false;}
public void puase(){paused = true;}
public MM_Timer(float delay, bool autostart){
delayy = delay;
if (!autostart) paused = true;
}
public MM_Timer(float minDelay, float maxDelay, bool autostart){
min = minDelay;
max = maxDelay;
if (!autostart) paused = true;
}
}
Just in case, my Script:
using UnityEngine;
using System.Collections;
public class bow : MonoBehaviour {
public GameObject arrow;
public Transform shotpos;
bool canfire = true;
public static float firerate = 0.5f;
MM_Timer timer = new MM_Timer (firerate, true);
void Update () {
if(Input.GetButton("Fire1")){
if(canfire){
Instantiate(arrow, shotpos.position, transform.rotation);
canfire = false;
}
}
if(timer.tick()){
canfire = true;
}
}
}
Answer by CHPedersen · Nov 10, 2014 at 09:09 AM
Update is a built-in method defined in class MonoBehaviour. It gets called automatically by Unity's runtime only in classes which derive from MonoBehaviour (we call those 'scripts'). These are the ones that can be attached to GameObjects.
You are free to define whatever code you like in any other object you like and call that as you see fit. But if it doesn't inherit (derive) from MonoBehaviour, Unity will not call those standard functions for you automatically. Given a reference to an object of type MM_Timer, you would have to simply call its Update method yourself.
You could call it inside the Update of a script that does inherit from MonoBehaviour, and couple it to Unity's framerate that way, if you wished.
Your answer
Follow this Question
Related Questions
How to destroy in an amount of time 1 Answer
Distribute terrain in zones 3 Answers
For loop resetting itself, but needs to stop 2 Answers
Multiple Cars not working 1 Answer