Add Instantiated object to a method in another class

I am very, VERY new to using Unity and Visual Studio. But in one of my classes, CellGrid, I have the method:

 public void AddUnit(Transform unit)
    {
        unit.GetComponent<Unit>().UnitClicked += OnUnitClicked;
        unit.GetComponent<Unit>().UnitDestroyed += OnUnitDestroyed;

        if(UnitAdded != null)
            UnitAdded.Invoke(this, new UnitCreatedEventArgs(unit));
    }

In another class, I instantiate a unit to the scene. Apparently I need to run that unit through this other method in order for the game to accept it as an actual player controlled piece. What I wrote was this:

GameObject summon = GetComponent<CardDisplay>().modelAnim;

Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);

        Vector3 worldPos;
        Ray ray = Camera.main.ScreenPointToRay(mousePos);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000f))
        {
            worldPos = hit.point;
        }
        else
        {
            worldPos = Camera.main.ScreenToWorldPoint(mousePos);
        }
Instantiate(summon, worldPos, Quaternion.identity, units.transform);

       CellGrid.AddUnit(summon.transform);

The instantiate works perfectly. I used a Vector3 and ScreenToWorldPoint to place it where I want and put it in the parent I want. But the ‘CellGrid.AddUnit(summon.transform);’ portion is busted. It wont even run unless I remove it completely.

Help?

You’re using the prefab/original in the AddUnit call, not the clone that comes from Instantiate. You want this:

GameObject clone = Instantiate(summon, worldPos, Quaternion.identity, units.transform);
CellGrid.AddUnit(clone.transform);

Hopefully that’ll fix whatever issue you’re having. “It’s busted” is a bit hard to diagnose. :wink:

1 Like

Nevermind… I’m just a noob. I didn’t directly reference CellGrid in that script yet, so of course it wasn’t going to work.