Search code examples
c#unity-game-enginegameobject

Unity C# - On button click pass gameobject to another C# script


I have multiple buttons with a different gameobject attached to them. When the button is clicked I want to pass the gameobject to another C# script which will after some conditions instantiate that passed gameobject. I have this code for the buttons:

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;

public class Element : MonoBehaviour
{
    private Button btn;
    public GameObject furniture;
    // Start is called before the first frame update
    void Start()
    {
        btn = GetComponent<Button>();
        btn.onClick.AddListener(PassObjectToAnotherScript);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void PassObjectToAnotherScript()
    {
        //Code to pass the object to another C# script
    }
}

The C# script to which the gameobject has to be passed to should have a:

private GameObject PassedGameObject;

Solution

  • It can be as simple as having the second script exposing a field or property that you can pass your object to. One of many ways to do this could look like this:

    public class Element : MonoBehaviour
    {
        private Button btn;
        public GameObject furniture;
        public Receiver recevier;
    
        void Start ( )
        {
            btn = GetComponent<Button> ( );
            btn.onClick.AddListener ( PassObjectToAnotherScript );
        }
    
        void PassObjectToAnotherScript ( )
        {
            //Code to pass the object to another C# script
            recevier.PassedGameObject = furniture;
        }
    }
    
    public class Receiver : MonoBehaviour
    {
        private GameObject _PassedGameObject;
        public GameObject PassedGameObject
        {
            get => _PassedGameObject;
            set
            {
                _PassedGameObject = value;
                Debug.Log ( $"Receiver[{name}] just received \'{_PassedGameObject.name}\'" );
            }
        }
    }