|
Let's say I have a base class like 'animal' and 3 subclasess like 'dog', 'cat', 'bird' Let's say the base has a function 'speak' that all 3 subclasses implement (bark, meow, chirp). Then these get added to prefabs. Now, I'd like to have a script be able to access the script component and call 'speak' and whatever the subclass happens to be, it will make the corresponding sound. Follow? So, can I just call gameObj.GetComponent(Animal).speak() ?? I would think Unity expects the exact class name (subclass), or GetComponent will fail.
(comments are locked)
|
|
In short I believe it ( I've got a Component Damageable that extends Monobehaviour. From that I have 2 components that extend from Damageable. DroneHealth and ShipHealth. DroneHealth and ShipHealth are attached to prefabs. In my collision test code I do
To get the component (the DroneHeralth or ShipHealth component that is, I never attach the Damageable component to anything). I then call applyDamage, which has the signature Bare bones versions of the components That's just what I needed, thanks!
Aug 20 '10 at 12:09 AM
DaveA
Although this answer was really helpful, it confused me a bit because of the RPC stuff which is not needed (as said but... well. I'm lost sometimes). All you need to do is: gameObject.GetComponent(); Thanks anyway. :)
Nov 13 '10 at 10:18 AM
Rodrigo Moraes
(comments are locked)
|
|
Sounds like you should be using SendMessage.
In that case it doesn't matter what the component is called. That may work, but my example above was simplified, I often need to set several variables, and SendMessage can have only one param, correct? Any idea if you can send a structure as that param?
Aug 19 '10 at 09:52 PM
DaveA
Actually, BroadcastMessage worked better for me. For some reason, even though objects using the SAME prefab, some got the message, some didn't, seems like a bug.
Aug 19 '10 at 10:17 PM
DaveA
SendMessage() is supposed to work only on the specified GameObject and its components, not any children or components connected to them; use BroadcastMessage to send a message to all children
Aug 19 '10 at 10:46 PM
Wolfram
@DaveA: yes, you can make a class with several elements and send that.
Aug 19 '10 at 11:18 PM
Eric5h5
Good to know, thanks
Aug 20 '10 at 12:10 AM
DaveA
(comments are locked)
|
