I am new to programming and I want to know whats the difference between a “static var something” and “gameobject.find().getcomponent().something”…
I always used the gameobject.find thing and it works fine but maybe it costs more performance? please tel me and I am sorry for asking such noob questions
A static variable is a direct reference and the other functions find references. Statics are therefore way faster - however they come with some pitfalls if you’re not sure what you are doing with them (for instance if you have an enemy Health script and you store the values in a static when one enemy dies, they all die).
You are best off using GameObject.Find - GetComponent in Start or Awake and caching the value in a non-static local variable which gives you the performance benefit without the overhead of understanding singletons. If you really only ever have 1 of an object then a static makes sense - if you have multiple you can use a static List to hold all the instances which is much faster than continually finding all of the game objects. E.g.
#SomeScript.js
static var all = new List.<SomeScript>();
function OnEnable()
{
all.Add(this);
}
function OnDisable()
{
all.Remove(this);
}
#SomeOtherScript.js
function Whatever()
{
//Loop through all of the instances of SomeScript
//that are active
for(var other : SomeScript in SomeScript.all)
{
//Do Something
}
}