- Home /
Must I attach every script to a gameobject in order to work ?
hello dear developers i have class called variables. When I use it in my collectmoney class i must attach variables class to a empty gameobject order to work(and I have to create get component to collectmoney class). But WHY cant we just simple not attach it(variables class) to a gameobject and only attach colllecmoney script to a coin(or money)(Coin is a gameobject like cube ) and simply works ? Must I attach EVERY script to a gameobject ?
Every class that inherits from $$anonymous$$onoBehaviour is a component and thus must be attached to a gameobject.
Answer by Igor_Vasiak · Aug 17, 2017 at 02:07 PM
You could simply remove MonoBehaviour from your variables class declaration. Then, to use it, write public Variables vars;, and you should be ready to go.
EDIT:
But, always remember: if it doesn’t work, write: public Variables vars = new Variables();
I tried but now it does not collect money it should say 5 than 10 15... but it stuck in 5 what can cause this ?
$$anonymous$$an... That's getting hard, since I don't have my computer to test it right now, but... Let's see what I can do for you.
Try to do this on a test scene just for testing sake. If it works, then your script should work, if you did everything alright.
public class $$anonymous$$yExample : $$anonymous$$onoBehaviour
{
public Variable vars;
void Update()
{
vars.money++;
Debug.Log("$$anonymous$$oney" + vars.money);
}
}
Answer by ClaudiusGoennus · Aug 17, 2017 at 01:33 PM
Try setting the variables class to static, then you should be able to reference it without an object reference.
You declare the class like this:
public static class staticClass : object
{
public static int count = 0;
public static int()
{}
}
And the you just reference the class by its name:
int i = staticClass.count;
If you want to learn more about c#, there's always this
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes