What is best practice when wanting to add to GameObject class?
I would like all GameObject to be able to change color IF they have a renderer. Ive tried using a helper class that takes a GameObject and lerps the color value but if i want it to have an update method it must inherit MonoBehaviour, and if it does inherit it then i cant instanciate that helper class.
Now im thinking about creating a new class that manages a GameObject and inherits from Monobehavoiur. It would have one GameObject as a member that it can manipulate. But then i would have to instanciate it from somewhere.
Hmmm unity has its logic but i havent found it yet. Is it clear what i am having problems with? Otherwise please ask.
If you’re programming in C#, you could also do an extension method for GameObject. I don’t know if it works for UnityScript… never tried.
Basically, you’d just have a static script like:
public static class GameObjectExtension{
public static void ChangeColor(this GameObject go, Color startColor, Color endColor){
Renderer renderer = go.renderer;
if(renderer == null)
//add renderer to go
/*lerping implementation here.*/
}
}
When you want to call it, just call your extension method as if it was a normal method in the GameObject class:
Monobehaviours can be instantiated, but not as normal classes ( no new ).
They do not have public constructors. They are “added” to GameObjects via the AddComponent method :
class MyScript : Monobehaviour
{
void Awake()
{
Debug.Log("My script awakes!");
}
}
class MyScriptFactory : Monobehaviour
{
void Start()
{
GameObject thisGameObject = this.gameObject; //just to show that every Monobehaviour being attached to a GameObject, this line is useless but valid.
MyScript myScript; // declare the reference.
myScript = thisGameObject.AddComponent( typeof ( MyScript ) ) as MyScript;
//Or using Generics ( requires using System.Collections.Generics )
myScript = this.gameObject.AddComponent<MyScript>();
}
}