Assign GameObject OnMouseUp not through inspector -2D

So I have a GameObject named “selectedUnit”, which can be moved across tiles via clicking. It works great when I drag a unit/object into the “selectedUnit” bit but that would mean that object will be forever selected.

Where as, realistically, there will be dozens of Units on screen, all with their own movement abilities and all of which can be controlled by the player. So the selectedUnit Object needs to be variable.

I’ve tried a dozen of tactics that I can think of and or find by researching online. Nothing seems to be able to assign the GameObject.

Currently I am instantiating the unit using this code

void GenerateUnitVisual(){
	UnitType ut = unitTypes [tiles [1, 1]];
	GameObject go = (GameObject)Instantiate (ut.unitVisualPrefab, new Vector3 (1, 1, 0f), Quaternion.identity);
	Unit u = go.GetComponent<Unit> ();
	u.unitName = ut.name;
}

Which is hard coding one unit to spawn but I will get to not hard coding it later once I get this working.

The UnitType instance, in this case “ut”, has two variables within in, name, and unitVisualPrefab, which are self explanatory.

The Unit class contains variables for x and y, for positions and UnitName, for the string name.

I’ve tried something along the lines of

selectedUnit.GetComponent<Unit>().unitName = GameObject.Find(unitName);

But that won’t work since the unitName is literally the variable name I made in UnitTypes.

I was wondering if something like

u.unitID = this;

But I always get some sort of error about can’t implicitly convert type to unit.

Regardless, I’m at a loss. Surely this should be simple. like
OnMouseUp(){selectedObject = this;} or something.

This can be done in a lot of different way.

Inside your main script (I will call it GameManger from now on), that allows your unit to move you can make a static variable, that works as the target or make your GameManager into a singleton, as I did in my example:

public class GameManager : MonoBehaviour
    {
    private static GameManager instance;

        public static GameManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = GameObject.FindObjectOfType<GameManager>();
                }
                return instance;
            }
        }
    
        public Unit Target { get; set; }
    }

On your UnitScript you can add the following:

private void OnMouseUp()
{
    GameManager.Instance.Target = this;
}

Personally I prefer to use a singleton over a static variable, but you can also just make a public static variable if you want to.