user1767754
user1767754

Reputation: 25154

Difference btw. sendmessage and setting Value

What is the difference between those two methods? Why should i prefer one?

1)

GameObject.FindGameObjectWithTag("").GetComponent<Rocket>().active = true;

2)

GameObject.FindGameObjectWithTag("").GetComponent<Rocket>().SendMessage("setActive");

thanks!

Upvotes: 0

Views: 880

Answers (2)

MichaelTaylor3D
MichaelTaylor3D

Reputation: 1665

Sending a message searches through all the components of the gameObject and invokes any function that has the same name as the message. Not a 100% sure but Im sure this uses reflection which is generally considered slow.

SetActive() or the active variable set the gameObject as active or not. If its not active it wont render in the scene and vice versa.

Upvotes: 1

Heisenbug
Heisenbug

Reputation: 39194

First of all it seems there are several inconsistencies with your code above:

1) Components (and MonoBehavior) don't have an active property (active belongs to GameObject), so the first line of code shouldn't compile. In addition the most recente version of unity don't have active anymore, it's substitued with activeSelf and activeInHierarchy.

And btw, both activeSelf and activeInHierarchy are read only, so you can't assing directly a value to them. For changing their value use SetActive method.

2) The second line of code shouldn't work either (unless Unity does some magic behind the scenes) because SetActive methods belong to GameObject and not to your Rocket Component.

Now, I suppose your question was the difference between:

gameObject.SetActive(true);

and

gameObject.SendMessage("SetActive",true);

The result is the same, but in the second way Unity3D will use reflection to find the proper method to be called, if any. Reflection has an heavy impact on performance, so I suggest you to avoid it as much as possible.

Upvotes: 0

Related Questions