i want a way to attach an event trigger to a button that i just instantiated with script and make it call functions from a specific object if pressed . how do i do that ? when i instantiate for some reason the object from which it should take the functions from is null so that’s why i wanna reasign it with script
Well you can add a lambda or delegate but you should be able to use GameObject.Find to find the GameObject and access its components.
I just instantiated a button and when clicked got it to change the color of a panel called TargetPanel.
This was on the prefab button and uses the prefab OnClick to call IveBeenClicked:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class InstButClick : MonoBehaviour {
private RectTransform myPanel;
// Use this for initialization
void Start () {
myPanel = GameObject.Find("TargetPanel").GetComponent<RectTransform>();
}
public void IveBeenClicked()
{
myPanel.GetComponent<Image>().color = Color.red;
}
}
And this instantiates the ButtonPrefab:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class InstButton : MonoBehaviour {
public GameObject prefabButton;
public RectTransform ParentPanel;
// Use this for initialization
void Start () {
GameObject goButton = (GameObject)Instantiate(prefabButton);
goButton.transform.SetParent(ParentPanel, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
}
}
When I click it the panel changes color. Basic I know but it appears to work, is your setup different in some way?