Can I add a script to prefab to access instantiated objects components?

Hi,

I have a prefab with about 20 children - text and sprites.
Can I add a script to it which on instantiating prefab it would generate references to the children’s components? So that on runtime I could change values without needing every time to find references.

For example:

-PanelPrefab
--Name_TextChild (UI Text)
--Description_TextChild (UI Text)
--Icon_ImageChild (UI Image)

Panel prefab assumably has a script.

On certain calling script an object is instantiated from prefab.

On instantiation script attached to prefab will get references to text and sprite components on Text and Image children.

Later I can instantly change these values from calling script via instantiated object by these references.

Yes, you can do that through a script.

You could either make a script that you apply to the prefab that hold all relevant references in advance, or you could look for them in Awake on that script. If you set the references up on the prefab through the inspector in advance, you don’t have to worry about changing names of children breaking your system.

I don’t know what your end goal is, but it can be nice to let the script also handle all requests you have for its children, so you don’t have to first get them and then apply the algorithm om them.

using UnityEngine;
using UnityEngine.UI;

public class YourPanelScriptExample : MonoBehaviour
{
    // Set the references in the inspector on the actual prefab...
    // If you really want to access the components directly, 
    // just make them plain old public instead...
    [SerializeField] private Text label;
    [SerializeField] private Text desc;
    [SerializeField] private Image icon;

    // ... Or call this method in Awake if you prefer to drive it through code.
    private void FindReferences()
    {
        label = FindReference<Text>("Name_TextChild");
        desc = FindReference<Text>("Description_TextChild");
        icon = FindReference<Image>("Icon_ImageChild");
    }

    // Just a helper to tidy the code a bit.
    private T FindReference<T>(string child) where T : Component
    {
        return transform.FindChild(name).GetComponent<T>();
    }

    // Access your data through properties if you want.
    public string Label { get { return label.text; } set { label.text = value; } }
    public string Description { get { return desc.text; } set { desc.text = value; } }
    public Sprite Icon { get { return icon.sprite; } set { icon.sprite = value; } }

    // Or add meaningful methods if you can think of any.
    // public void ChangeSelectedItem(ShopItem item)
    // {
    //    PlayNewSelectionSound();
    //    HighlightPurchaseButton();
    //
    //    Label = item.name;
    //    Description = item.desc;
    //    Icon = item.icon;
    // }
}