Seting parent of prefab error

hi, I looked around a bit and couldn’t seem to find an answer. I am trying to instantiate a unit on a tile game and set it as the parent when it spawns(or child) but i get the error “Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption” is there a way around this or am i simply doing it wrong? the error comes from line 21.
thanks for any input

    private void SpawnUnitOnTile()
    {
        if (Input.GetMouseButtonUp(0) && KnightSpawnCount < 3)
        {

            RaycastHit hit;
           
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
            {
               
                if(hit.transform.gameObject.tag == "Tile")
                {
                    Debug.Log(hit.transform.gameObject.name);
                    Debug.Log(hit.transform.position);

                    Quaternion layoutRotation = Quaternion.Euler(0f, -90f, 0f);
                    Instantiate(UnitOnTile, new Vector3(hit.transform.position.x, 1.1f, hit.transform.position.z), layoutRotation);

                    //UnitOnTile.transform.parent = hit.transform;

                    UnitOnTile.transform.SetParent(hit.transform);

                    KnightSpawnCount++;

                   
                }
               
            }
           
        }
       
    }

You’re trying to set the parent of the prefab. What you want to do is set the parent of the new instance you created. Instantiate will return the reference to the newly created object. Try this:

var newUnit = Instantiate(UnitOnTile, new Vector3(hit.transform.position.x, 1.1f, hit.transform.position.z), layoutRotation);
newUnit.transform.SetParent(hit.transform);
1 Like

Yo sorry for the late response, went to bed right after posting, was dinking with that for ever. Thanks! your solution worked perfectly.