Search Unity

How to reference 2 prefabs that instantiate during start?

Discussion in 'Prefabs' started by Lenx23, Jul 5, 2021.

  1. Lenx23

    Lenx23

    Joined:
    Oct 12, 2020
    Posts:
    14
    Hi;

    I have a player prefab and a canvas prefab, how would I add ex. images from canvas prefab to a serialized field on player prefab (btw. I have multiple player prefabs that you can choose from and instantiate them with the help of Player Prefs).
    I can not drag and drop it since it is a prefab that is instantiated during play.

    Also, how can I do the opposite place player prefab on canvas prefab? I made it like a game object that uses "FindObjectOfType" but I don't think that is the best option. Is that even possible or should I not place canvas a prefab?
    Should I use scriptable objects and if so then where?

    Thank you for your answer.
     
  2. DerDicke

    DerDicke

    Joined:
    Jun 30, 2015
    Posts:
    292
    If you only have only one Canvas for the functionality given, save it in a static public variable in Awake(). Like:

    class SomeCanvasInfo: public MonoBehavior
    {
    static public SomeCanvasInfo someCanvasInfo;

    void Awake()
    {
    someCanvasInfo= this;
    }
    }


    In your Players, do:

    class SomePlayer: public MonoBehavior
    {

    void Update()
    {
    if (SomeCanvasInfo.someCanvasInfo != null)
    {
    // do something
    }
    }


    This is called a Singleton.
     
  3. Lenx23

    Lenx23

    Joined:
    Oct 12, 2020
    Posts:
    14
    Thx, so make a canvas singleton is the best option, in this case, better than use FindObjectOfType?
     
  4. DerDicke

    DerDicke

    Joined:
    Jun 30, 2015
    Posts:
    292
    Probably in almost any case. Keep in mind that this will not hinder you to create more canvasses. Just use a custom script as Singleton and operate from it.
     
    Lenx23 likes this.
  5. Lenx23

    Lenx23

    Joined:
    Oct 12, 2020
    Posts:
    14
    Thank you very much :D