x


Call Function in unknown Class

Hello, I'm trying to call a function from a class of an object. I have the Object but no clue to access the right Component.

A little Example:

public class Heal : Effect {
    public void ApplyEffect(GameObject user, int amount) {
       print("Healing " + user.name + " for " + amount);
    }
}

Thats the Method I want to Call from this:

public class ItemPotion : Item {
    public GameObject _effect;
    public int _value;

    public void Use(GameObject user) {
       Type component = ???
       component.ApplyEffect(user, 25);
    }
}

I cant call it with GetComponent() because it should work with any other class as well. When I call the Method, I know the Method is there because every class from Effect has this one, but I dont know the concrete Name of the Class.

Hope you can Help.

more ▼

asked Jun 23 '12 at 06:28 PM

Huma gravatar image

Huma
17 1 3

Ok - so the effect is related to the game object _effect how?

Jun 23 '12 at 06:30 PM whydoidoit

I have an Object for each xyzEffect and an Object for each Item. If I want to create a new Potion I drag and drop the effects I want to assign to it in the Inspector.

Jun 23 '12 at 07:13 PM Huma
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

I know the Method is there because every class from Effect has this one

Are you saying that all of your effects inherit from Effect? Does Effect inherit from Component (or perhaps MonoBehaviour)? If so, you can still use calls like _effect.GetComponents<Effect>() to get a full list of them. You could write ApplyEffect() as a virtual method in Effect, and have each effect class override it.

If you're having trouble understanding the above, you may want to read up on polymorphism, which is one of the most important principles in object-oriented programming. For starters, here's an MSDN guide on override methods.

And, finally, if you can't get that working, there is always SendMessage().

more ▼

answered Jun 23 '12 at 06:59 PM

rutter gravatar image

rutter
5.2k 2 11

"_effect.GetComponents() to get a full list of them. You could write ApplyEffect() as a virtual method in Effect, and have each effect class override it."

Thats weird, thought I already tried this. Tried around with GetComponents() and overriding, must have missed the right combination of both with some other things I tried. ;)

Works pretty well, thanks for the answer. I also will keep SendMessage in mind for the future. =)

Jun 23 '12 at 07:46 PM Huma
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x337
x234
x55

asked: Jun 23 '12 at 06:28 PM

Seen: 404 times

Last Updated: Jun 23 '12 at 07:46 PM