Search Unity

Assigning GameObject to script component variable of instantiated prefab?

Discussion in 'Editor & General Support' started by Morfic, Nov 16, 2020.

  1. Morfic

    Morfic

    Joined:
    Nov 15, 2020
    Posts:
    3
    I apologize in advance for asking a question that has been asked before on here. But I have tried to figure this out on my own with those previous articles to no avail.

    I am currently instantiating a prefab with a component attached. When it gets added, the field is blank. So I have a need to attach the target to the component as it gets instantiated. For whatever reason it is not working. Here are the scripts:

    This script works fine, and defines the "Background" component, in which I drag and drop my actual background GameObject into the field.


    Code (CSharp):
    1.  using UnityEngine;
    2.      using System.Collections;
    3.    
    4.      public class ObjectMovement : MonoBehaviour
    5.      {
    6.          public GameObject Background;
    7.    
    8.          // Use this for initialization
    9.          void Start ()
    10.          {
    11.          }
    12.        
    13.          // Update is called once per frame
    14.          void Update ()
    15.          {
    16.              BGScroll scrollScript = Background.GetComponent<BGScroll>();
    17.             // Debug.Log(scrollScript.scroll_Speed);
    18.              GetComponent<Rigidbody2D>().transform.Translate(0, scrollScript.scroll_Speed / 4, 0);
    19.          }
    20.      }
    This is the script in which I am trying to add the GameObject "background" into the "Background" component field. You can see a few of the tests I have tried commented out.

    Code (CSharp):
    1. using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.  
    5.     public class SpawnHazards : MonoBehaviour
    6.     {
    7.         public GameObject obj;
    8.  
    9.         // Start is called before the first frame update
    10.          void Start()
    11.         {
    12.             SpawnWaves();
    13.         }
    14.      
    15.         void SpawnWaves()
    16.         {
    17.             Vector3 position = new Vector3(Random.Range(-1.8f, 1.8f), -8, 0);
    18.             var createdObj = Instantiate(obj, position, Quaternion.identity);
    19.             //ObjectMovement myScript = obj.GetComponent<ObjectMovement>();     <--- First attempt
    20.             //myScript.Background = background;                                 <--- First attempt
    21.  
    22.             //GameObject ObjectMovement = GameObject.FindGameObjectWithTag("Background");               <--- Second attempt
    23.             //ObjectMovement.GetComponent<ObjectMovement>().background();                               <--- Second attempt
    24.  
    25.         }
    26.     }
    In the last test I ran (attempt 2), I got the error "'ObjectMovement' does not contain a definition for 'background'

    It looks like in my tests, that I am trying to look for a "background" within the ObjectMovement script. But rather, the "background" I am trying to set as the variable in the prefab component, is just the background game object that exists in the hierarchy. I hope all that made sense.
     

    Attached Files:

  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Your "first attempt" looks fine to me, with the exception that the "background" object you're assigning to myScript.Background isn't defined in the code you provided, but I assume you just didn't include every line of code in your sample here.

    Can you be specific about what isn't working with that approach? If you're getting errors in the console, say what they are. But the general approach you've shown here should be fine.

    As a side node, the Update method of your ObjectMovement class makes a couple of GetComponent calls. That's okay initially, but that kind of approach isn't usually recommended, for performance reasons. You're better off assigning the result of the GetComponent calls to private class variables once, to avoid having to call GetComponent every frame. I doubt this is at all related to your issue, but it's just good practice.
     
  3. Morfic

    Morfic

    Joined:
    Nov 15, 2020
    Posts:
    3
    Thank you very much for the reply. I included every line of my code. So I probably just didn't know to add whatever would be needed.

    So my initial error is, when I test the project, it instantiates the object with my custom script component attached. But for it to function, I need to drag and drop my "background" game object from the hierarchy into the component variable field. So it says, "The variable Background of ObjectMovement has not been assigned."

    Then when trying that "First Attempt", I got the error, "The name 'background' does not exist in the current context".

    I see what you mean about the ObjectMovement Update section. I will do some research on getting that corrected for best practices. Thank you!
     
  4. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Well, you need to make put a "background" property on SpawnHazards so it has something to assign to the instantiated objects. Maybe just add
    public GameObject Background;
    to SpawnHazards, assign it a game object in the inspector, and then on line 20 of SpawnHazards you can assign Background to the ObjectMovement instance.

    That's a start, anyway.
     
    Morfic likes this.
  5. Morfic

    Morfic

    Joined:
    Nov 15, 2020
    Posts:
    3
    Actually, you were right. All I was missing was defining the background object. I feel extremely silly about taking this long troubleshooting something so silly. Thank you so much for steering me in the right direction.
     
    dgoyette likes this.