Question about getComponent()

I’m using getComponent(“Foo”) such as:

Foo bar = _bar[0].transform.parent.GetComponent(“Foo”) as Foo;

and Foo has been running in the simulation for a while, and has variables populated in it.

Will bar be an instantiation of a new bar(), or will the variables on bar be populated?

The best way to learn this stuff is to try it and learn. But, as a general rule, any “GetXYZ” type function in any API that’s half decent will always give you things that already exist if they can, unless they specify otherwise. In this case it’ll give you a reference to the Foo that already exists and has your variables in it.

It’s a reference to the script that’s attached to Foo, not a new instance of anything. By the way, don’t use strings in GetComponent. If you’re using C#, do “GetComponent”. In Unityscript, do “GetComponent(Foo)”.

–Eric

What you are doing is making an object of the type Foo named bar. Therefore, bar will be an instance of Foo().
When you grab the component “Foo” and typecast the variable bar as Foo, you are saying you want a new instance
of that class / type. With the instantiated object bar, you can make calls to the data members and methods using
the dot operator like so: bar.Whatever() or bar.dataMember1, etc.

As mentioned above, the proper way to grab the component in C# is objectName.GetComponent();

Sometimes, you may need to typecast the component as you did when you said “as Foo”.

Nope, it’s a reference (sort of like a pointer), not a new instance. Nothing is instantiated.

If you use the generic version, then it’s already cast as the correct type and you will never need to use “as”.

–Eric

It all worked. Thanks guys.