- Home /
reference an object that is yet to be in the scene
I want to reference an object's transform through code that would change, deactivate activate and leave scene, the scene will start without it and then will be added and removed freely, here is one for my codes that have the problem, please help and thanks. Note: I placed it in the update because as I said the object will change and leave the scene and so on, and for start it is only called once.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Target : MonoBehaviour
{
private Transform target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (target == null)
{
target = GameObject.Find("Aim").GetComponent<Transform>();
}
if (target!= null)
{
transform.position = target.position;
}
}
}
,I am trying to make a script that reference an objects transform that does not exist in the scene in start but spawns later and remove it freely without getting any null error, here is one of the codes I am using. Any help? Thanks.
Answer by niklasdette · Sep 15, 2019 at 06:51 PM
You could put a script on the Object that you want to spawn, and then access your "Target" Script from there.
First set your Transform "target" to public.
public Transform target;
Then you could make your "Target" Script to an instance, then you can acces it very easy from other scripts. For that :
public static Target instace;
Awake()
{
instance = this;
}
Now, when you spawn the other object, you can have a script on it with something like this:
Awake()
{
Target.instance.target = transform;
}
This will put the own transform in the "target" variable of the "Target" Script, when you spawn it.
Hope I could help you :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612212159im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
PlayFab CloudScript NullReferenceException 0 Answers
How to make sounds louder if I go faster 1 Answer
How to nine slice a 2D SpriteRenderer? 0 Answers