I just want to create a new script object. I need for its Update() function to be called at the very least. What must
I do to make this happen?
I’ve tried Timer inputUseTimer = new Timer(); but then the Update() function never gets called, I’ve tried typing in Instantiate() but its wrong because that function doesn’t take that kind of argument (my Timer class).
Again, how?
Create Monobehaviours using AddComponent, don't use constructors. Timer inputUseTimer = (new GameObject()).AddComponent< Timer >();
Create Monobehaviours using AddComponent, don’t use constructors.
Timer inputUseTimer = (new GameObject()).AddComponent< Timer >();
For future readers, what I'm going to do is just attach my Timer class as a component to each gameobject which needs a Timer. I accepted this one as the answer because Eric replied first with a good answer, and other ideas weren't possible.
In case Bonfire Boy’s answer isn’t clear I’ve added some code as an example
using UnityEngine;
using System.Collections;
//This would be the main object that you want to attach the timer to
public class MainObject : MonoBehaviour {
public Timer inputUseTimer ;
// Use this for initialization
void Start () {
timer = gameObject.AddComponent<Timer>();
timer.InitialiseValues(/* Your arguments */);
}
}
/***********************************************/
using UnityEngine;
using System.Collections;
using System;
//This is the Timer object
public class Timer : MonoBehaviour {
void Update () {
//Do stuff
}
public void InitialiseValues(/*Your arguments*/)
{
//Assign the values you need
}
}
/****** End *************/
gameObject.AddComponent<>() will create a new instance of the script and attach it to the object that called it.
When it comes to using Instantiate() you used that for prefabs and gameobjects stored as fields to create clones of them.
These are all really great answers. I was hoping for something much cleaner though. Something where I wouldn't have to declare a separate object variable like another gameobject just to attach a Timer script object to. Would it be possible to forgo the inheriting of monobehaviour and just use some .net calls to achieve this? The only reason I wanted to use MonoBehaviour was it would call Update() automatically and that way I could update the time there and check to see if the timer was done. Is that possible?
You can not new a component object by youselft. Update function called by GameObject. Componet shoud be handled by GameObject instances. So would be like this
GameObject obj = new GameObject();
obj.AddComponent<T>();
Create Monobehaviours using AddComponent, don't use constructors. Timer inputUseTimer = (new GameObject()).AddComponent< Timer >();
– Bonfire-Boy