GAMEOBJECT AS ARGUMENT LOSS REFERENCE WHEN CALLING THE FUNCTION EITHER FROM ITS CLASS OR OUTSIDE CLASS.

Please help !

Here is my code

Script1

Public class Test1: Monobehaviour{

Public GameObject buttonprefab;
Public Transform grid;
Public delegate void Functionreturntype();



public void SpawButton(GameObject clone, string buttonname, Functionreturntype)
{
Clone = (GameObject) Instantiate (buttonprefab,grid);
Button button = clone.GetComponets();
Butto .onClick.AddListener(delegate {Function type};});
TextMeshProGUI buttontext = button.GetComponetInChildren();
Buttontext.text = buttonname;

}

}

Scrip2

Public class Test2: Monobehaviour{

Public Test1 test1;
Public GameObject myclone;

Void Start   ( ){
Test1.SpawButton(myclone,"opendoor", Opendoor);

}

Void Opendoor(){ 
Debug.Log("opening") ;
 }


}

Everything works fine and I get no error.
The idea is to be able to delete clone button
whenever I want to but the problem is that ‘clone’ from “script 1” never equal to clone of "script 2 " which is weird because I’m unable to delete the clone button whenever I call the function.
I also tested it in inspector no luck.

Hello.

You talk about destroy the clone, but i dont see any destroying code, only spawning.

I dont iunderstand your code…

You talk about so many difernt variables :

in script 1 you have :

Clone
clone

In script 2:

myclone

why you call SpawButton() using myclone from script 2. But then in script 1 instantiate a prefab stored there and create a new variable called Clone ??

dont get what you want to do…


UPDATE


For your comments, then you just need to create a public variable in Script 1, and assign the new created clone in that variable, so from script 2 can reach thet object adn destroy it when you weant.

when you instantiate something, you can define it in a variable. This is the sctructure:

Script1:

public GameObject NewObject;
NewObject = Instantiate (prefab, pos, rot);

Script2:

Destroy(Script1.NewObject);