Add Custom property to GameObject (C#)


I’ve seeing many topics with this subject, but all answer doesn’t works like I would like.
My goal is to create a custom property for many GameObject and check value on a main script for each.

// Attached to all GameObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class AddProperty : MonoBehaviour
    public int Stars = 4;

GameObject[] rootGOs = UnityEngine.Object.FindObjectsOfType<GameObject>();
        foreach (GameObject g in rootGOs)
            Debug.Log(g.Stars); //Error
            Debug.Log(g.GetComponent<AddProperty>().Stars; //Error

// Error : GameObject' does not contain a definition for 'Stars' and no accessible extension method 'Stars' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

Do you have an idea to fix my situation ?
Thanks you !
Best Regards

Hi @vincentbts, what you want to do is create an extension method called Stars which returns you the requested Integer. To achieve this we will first create the following code:

public static class GameObjectExtensions
    private static int _stars = 0;

    public static int Stars(this GameObject gameObject)
        return _stars;
    public static void AddStar(this GameObject gameObject, int numberToAdd)
        _stars += numberToAdd;

After that is put into a script it can be referenced on a GameObject instance. Here is an example of how to call it (tested in Unity and working as intented):

void Start()
        print("There are currently " + gameObject.Stars().Count + " stars.");

Keep in mind that this means that EVERY GameObject in your game will have this variable. Hope this helps.