- Home /
SendMessage to multiple objects
Hey guys,
Quick question: I've designed something like a World of Warcraft-styled hotbar for my game. The way it works is that it's just 10 planes that should show the texture of the item that's put in that slot.
So the way I set this up is that I have a 'refreshTextures' function that just goes through stuff like:
if(item == "Potion"){ renderer.material.mainTexture = GameObject.Find("inventory").GetComponent(inventory).Potion;}
Now, all of this works just nicely. The problem is that I have 10 planes and the that function has to be called 10 times (for each plane). So what I want to do is:
If Player picks up Item, assign texture to hotbar slot(I already set that up) and then refresh all the hotbar textures.
Every single hotbar slot should receive the 'refreshTextures' message from the pickup, but every time I do it only the LAST hotbarSlot with the name, tag, variable, etc. actually changes its texture.
Isn't there a simple, non-convoluted way of sending out a message to MULTIPLE objects that then call a function at the same time?
Answer by CHPedersen · Jul 27, 2011 at 01:26 PM
There is - Maybe you want something like BroadcastMessage?
http://unity3d.com/support/documentation/ScriptReference/Component.BroadcastMessage.html
It calls the method whose name you supply with the argument you supply on the target object itself and all of its children, so whether it would work for you depends a little on how you have your gameobjects parented in your project.
You could definitely use it if your hotbarSlots are independent GameObjects, which are all children of the same parent GameObject (Hotbar). Then, you'd call BroadcastMessage on the Hotbar's script, and it should execute refreshTextures on all of its child hotbarSlots.
Thanks, that did it. I just re-parented a couple of things, do direct references on stuff and then broadcast the message to the parent. Seems to be fast enough :)
Answer by PaulUsul · Jul 27, 2011 at 01:30 PM
You should read up on OOP(Object-oriented programming), it's a way of thinking and writing code that solves problems just like this one!
To the question, you could hold your items in an array and loop over them. It's also a lot faster then GameObject.Find and SendMessage.
Caching script instances has only a $$anonymous$$or impact in this case, because he's not continually calling his refreshTextures-method. It only happens when the player picks something up. Broadcasting is fine in that case.
So true. I still wouldn't use Broadcast even though it fits the problem. Because the lack of type safety and extensibility.
Your answer
Follow this Question
Related Questions
SendMessageUpwards - Send Multiple Parameters? 3 Answers
Accessing an Array in another function 1 Answer
SendMessage with multiple parameters 3 Answers
Multiple rotations with Quaternion Slerp problem 0 Answers
multiple paths 1 Answer