Search Unity

Add Instantiated object to a method in another class

Discussion in 'Scripting' started by Aerhart941, Apr 20, 2019.

  1. Aerhart941

    Aerhart941

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

    Code (CSharp):
    1.  public void AddUnit(Transform unit)
    2.     {
    3.         unit.GetComponent<Unit>().UnitClicked += OnUnitClicked;
    4.         unit.GetComponent<Unit>().UnitDestroyed += OnUnitDestroyed;
    5.  
    6.         if(UnitAdded != null)
    7.             UnitAdded.Invoke(this, new UnitCreatedEventArgs(unit));
    8.     }
    9.  
    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:

    Code (CSharp):
    1.  
    2.  
    3. GameObject summon = GetComponent<CardDisplay>().modelAnim;
    4.  
    5. Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);
    6.  
    7.         Vector3 worldPos;
    8.         Ray ray = Camera.main.ScreenPointToRay(mousePos);
    9.         RaycastHit hit;
    10.         if (Physics.Raycast(ray, out hit, 1000f))
    11.         {
    12.             worldPos = hit.point;
    13.         }
    14.         else
    15.         {
    16.             worldPos = Camera.main.ScreenToWorldPoint(mousePos);
    17.         }
    18. Instantiate(summon, worldPos, Quaternion.identity, units.transform);
    19.  
    20.        CellGrid.AddUnit(summon.transform);
    21.  
    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?
     
    Last edited: Apr 20, 2019
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You're using the prefab/original in the AddUnit call, not the clone that comes from Instantiate. You want this:
    Code (csharp):
    1.  
    2. GameObject clone = Instantiate(summon, worldPos, Quaternion.identity, units.transform);
    3. CellGrid.AddUnit(clone.transform);
    4.  
    Hopefully that'll fix whatever issue you're having. "It's busted" is a bit hard to diagnose. ;)
     
    Aerhart941 likes this.
  3. Aerhart941

    Aerhart941

    Joined:
    Apr 7, 2019
    Posts:
    61
    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.