-1

I'm trying to add an extension method to my gameobject, that's works, but my problem is the GameObject share the same result. My goal is to have a different result for each GameObject.

// AddExtension.cs
public static class GameObjectExtensions
{
    private static int life;
    public static int Life(this GameObject gameObject)
    {
        return life;
    }
    public static void ChangeLife(this GameObject gameObject, int numberToAdd)
    {
        life += numberToAdd;
    }
}

And in my main code, I would like to manage GameObject like :

void Start()
{

    GameObject.Find("Perso0").ChangeLife(2);
    GameObject.Find("Perso1").ChangeLife(4);


    GameObject[] rootGOs = UnityEngine.Object.FindObjectsOfType<GameObject>();
    foreach (GameObject g in rootGOs)
    {
        if(g.name == "Perso0")
        {
            Debug.Log("Perso0 : " + g.Life());
        }
        if(g.name == "Perso1")
        {
            Debug.Log("Perso1 : " + g.Life());
        }
    }
}

But both GameObject have 6 in "Life" ( 2 + 4 ) I whould like to get only 2 for "Perso0" with Life and 4 with "Perso1" with Life Do you have some clue to helping me ?

Thank you and best Regards

twenty94470
  • 105
  • 2
  • 12

2 Answers2

1

Because your life variable is static, it's going to be the same value you're editing every time you call ChangeLife on a GameObject.

Since extension methods need to belong to static classes, and a static class can only have static members, you cannot achieve the goal you want with extension methods.

Even if you could, it's not the right way to go with the Unity paradigm. With this setup, you're essentially saying "Every GameObject in my scene has a life value," which I don't think you want to do.

Instead, you can create your own components, as below.

public class Enemy : MonoBehaviour
{
    [SerializeField] private int _initialHealth = 100;

    private int _health = -1;

    public int health { get { return _health; } }

    private void Awake()
    {
        _health = _initialHealth;
    }

    public void IncrementHealth(int health)
    {
        _health += health;
    }
}

This is just an example, but you can make something to suit your needs.

Aaron Cheney
  • 134
  • 2
0

static applied to a member means all instances share a single copy. That is, there's only one life variable, which is modified when you call ChangeLife() on any GameOject.
Since extension methods have to be in a static class, I don't think you can accomplish what you want this way.

However, you should be able to add custom properties to your players and other objects in Unity. I don't remember if they're called "custom properties" exactly, but I know some of the basic tutorials like Roll-a-Ball cover this (or at least used to).

David
  • 2,226
  • 32
  • 39