Unassigned reference exception unity ошибка

MaxiD

-9 / 1 / 0

Регистрация: 02.05.2018

Сообщений: 79

1

12.08.2018, 17:04. Показов 49972. Ответов 13

Метки error, unity 3d (Все метки)


Студворк — интернет-сервис помощи студентам

Выдаёт ошибку в unity, вот текст ошибки: UnassignedReferenceException: The variable ObjectToSpawn of ObjectSpawner has not been assigned.
You probably need to assign the ObjectToSpawn variable of the ObjectSpawner script in the inspector.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot)
UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:211)
UnityEngine.Object.Instantiate[GameObject] (UnityEngine.GameObject original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:285)
ObjectSpawner.Spawn () (at Assets/Scripts/ObjectSpawner.cs:37)
ObjectSpawner+<Spawner>c__Iterator0.MoveNext () (at Assets/Scripts/ObjectSpawner.cs:30)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

Вот код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ObjectSpawner : MonoBehaviour {
 
    public bool isSameDelay;
    public bool isRandomObject;
    public GameObject ObjectToSpawn;
    public GameObject[] ObjectsToSpawn;
    public float timeBeforeSpawn;
    public float spawnDelay;
    public float minDelay;
    public float maxDelay;
 
    private void Start () {
        if(isSameDelay)
        {
            InvokeRepeating("Spawn", timeBeforeSpawn, spawnDelay);
        }
        else
        {
            StartCoroutine(Spawner());
        }
    }
 
    private IEnumerator Spawner()
    {
        yield return new WaitForSeconds(Random.Range(minDelay, maxDelay));
        Spawn();
    }
 
    private void Spawn()
    {
        if(!isRandomObject)
        {
            GameObject obj = Instantiate(ObjectToSpawn, transform.position, transform.rotation) as GameObject;
        }
 
        if (isRandomObject)
        {
            GameObject obj = Instantiate(ObjectsToSpawn[Random.Range(0, ObjectsToSpawn.Length)], transform.position, transform.rotation) as GameObject;
        }
 
        if(isSameDelay)
        {
            StartCoroutine(Spawner());
        }
    }
}



0



33 / 32 / 10

Регистрация: 07.08.2012

Сообщений: 148

12.08.2018, 17:13

2

Выделяйте код тегом C#

У вас этот скрипт к какому — либо объекту прикреплен ? Если нет , создайте «пустой» и прикрепите.



0



1 / 1 / 0

Регистрация: 30.08.2015

Сообщений: 10

12.08.2018, 17:18

3

Ты забыл в инспекторе назначить объект в ObjectToSpawn.



0



Askfor

33 / 32 / 10

Регистрация: 07.08.2012

Сообщений: 148

12.08.2018, 17:26

4

Цитата
Сообщение от Maxim_77
Посмотреть сообщение

Ты забыл в инспекторе назначить объект в ObjectToSpawn.

кстати да.. но я уже исправиться не успел )

MaxiD
Еще это можно сделать так.

C#
1
ObjectToSpawn = GameObject.FindGameObjectsWithTag("objSpawn");

То что в кавычках нужно вписать свое, предварительно назначив Tag этому объекту, тогда по идее в инспекторе можно не добавлять вручную. И присваивание это должно быть до вызова вашего Spawn().



0



MaxiD

-9 / 1 / 0

Регистрация: 02.05.2018

Сообщений: 79

12.08.2018, 17:31

 [ТС]

5

Даже когда назначаю все равно ошибка.

Добавлено через 52 секунды
Ошибка указывает на строку

C#
1
            GameObject obj = Instantiate(ObjectToSpawn, transform.position, transform.rotation) as GameObject;



0



1 / 1 / 0

Регистрация: 30.08.2015

Сообщений: 10

12.08.2018, 17:35

6

Цитата
Сообщение от MaxiD
Посмотреть сообщение

Даже когда назначаю все равно ошибка.

У себя проверил. Ошибка исчезла. Проверь еще раз, объект должен быть назначен, об этом как раз и написано в тексте ошибки «You probably need to assign the ObjectToSpawn variable of the ObjectSpawner script in the inspector».



0



-9 / 1 / 0

Регистрация: 02.05.2018

Сообщений: 79

12.08.2018, 17:38

 [ТС]

7

Тема закрыта я проблему решил сам!

Добавлено через 17 секунд
Всем спасибо за помощь!



0



1 / 1 / 0

Регистрация: 30.08.2015

Сообщений: 10

12.08.2018, 17:44

8

Цитата
Сообщение от MaxiD
Посмотреть сообщение

Тема закрыта я проблему решил сам!

Как решил-то? Может у кого-то такая же проблема будет.



0



33 / 32 / 10

Регистрация: 07.08.2012

Сообщений: 148

12.08.2018, 17:44

9

Ну так показывайте решение, иначе смысл писанины.



0



0 / 0 / 0

Регистрация: 07.04.2016

Сообщений: 3

13.11.2018, 12:13

10

Цитата
Сообщение от MaxiD
Посмотреть сообщение

Тема закрыта я проблему решил сам!

Добавлено через 17 секунд
Всем спасибо за помощь!

я бы руки таким поотрывал… ну решил ты проблему — скажи всем как!!!! чтож за быдлокодерская привычка



0



15 / 8 / 7

Регистрация: 22.02.2018

Сообщений: 85

Записей в блоге: 1

13.01.2019, 13:10

11

заскринил решение

Миниатюры

Необычная ошибка UnassignedReferenceException
 



1



2 / 2 / 0

Регистрация: 03.02.2022

Сообщений: 6

03.02.2022, 13:19

12

Эта проблема возникает, когда этот скрипт висит на более, чем одном объекте. И на одном из них не указан выделенный компонент.
Решение:
Кликаем на проблемный скрипт правой кнопкой мыши, жмём Find of Scence, в иерархии останутся только объекты с этим скриптом. И проверяем, что во ВСЕХ объектах всё стоит верно, нет пустых окон. Особое внимание уделяем задвоенным скриптам. Я попался на этом. на одном объекте — один скрипт!



2



627 / 461 / 203

Регистрация: 05.04.2015

Сообщений: 1,838

03.02.2022, 13:35

13

Survir, зачем постить, теме 3 года



0



0 / 0 / 0

Регистрация: 15.12.2019

Сообщений: 7

16.03.2023, 17:27

14

zhunshun, зато этот коммент помог как минимум одному человеку в 2023)



0



I’m super new to coding and to this forum so forgive me if I break any taboo’s here. I’m simply working on a 3rd person camera, just kind of messing around but I keep getting

UnassignedReferenceException: The variable CameraFollowObj of CameraFollow has not been assigned.
You probably need to assign the CameraFollowObj variable of the CameraFollow script in the inspector.
CameraFollow.CameraUpdater () (at Assets/Scripts/CameraFollow.cs:68)
CameraFollow.LateUpdate () (at Assets/Scripts/CameraFollow.cs:62)»

I’ve created an object for my camera to follow and placed it on the model. Then moved the object to what I believe to be the correct field but the issue still persists.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public float CameraMoveSpeed = 120.0f;
    public GameObject CameraFollowObj;

    Vector3 FollowPOS;

    public float clampAngle = 80.0f;
    public float InputSensitivity = 150.0f;
    public GameObject CameraObj;
    public GameObject PlayerObj;
    public float camDistanecXToPlayer;
    public float camDistanecYToPlayer;
    public float camDistanecZToPlayer;
    public float mouseX;
    public float mouseY;
    public float finalInputX;
    public float finalInputZ;
    public float smoothX;
    public float smoothY;

    private float rotY = 0.0f;
    private float rotX = 0.0f;

    // Start is called before the first frame update
    void Start()
    {
        Vector3 rot = transform.localRotation.eulerAngles;
        rotY = rot.y;
        rotX = rot.x;
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float InputX = Input.GetAxis("RightStickHorizontal");
        float InputZ = Input.GetAxis("RightStickVertical");
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");
        finalInputX = InputX + mouseX;
        finalInputZ = InputZ + mouseY;

        rotY += finalInputX * InputSensitivity * Time.deltaTime;
        rotX += finalInputZ * InputSensitivity * Time.deltaTime;

        rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

        Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
        transform.rotation = localRotation;
    }

    void LateUpdate() 
    {
        CameraUpdater();
    }

    void CameraUpdater() 
    {
        Transform target = CameraFollowObj.transform;

        float step = CameraMoveSpeed * Time.deltaTime;
        transform.position = Vector3.MoveTowards (transform.position, target.position, step);
    }
}  

derHugo's user avatar

derHugo

80.7k9 gold badges70 silver badges110 bronze badges

asked Aug 29, 2019 at 5:00

helplesscodenub's user avatar

1

Make sure you haven’t added the script to another gameobject somewhere else in the project that might cause this error.
You can search for the script in the scene search bar and all the gameObjects with the script attached will appear. Also in runtime if you right click on the script and in the contextual menu you select option kind of «find all the references in the scene» or something similar, you get all the instances of the script in your scene.

I think you should have drargged the script into another gameObject by mistake where the cameraToFollow gameObject is empty so you get the unnasigned error.

Hope this helps.

answered Aug 29, 2019 at 5:55

rustyBucketBay's user avatar

rustyBucketBayrustyBucketBay

4,2401 gold badge16 silver badges46 bronze badges

3

There are multiple things you can try to do:

  1. Make sure you dragged the correct object in the field (I doubt that your character object is called CameraFollow)
  2. Make sure that you dragged in an object from the Hierarchy and not the Assets window (ethats means that you need to drag in objects that are currently in the scene and can be seen on the hierarchy)
  3. If you try everything from above and it doesen’t work try assigning the object in the start function of the script. You can use GameObject.Find

Hope this helped to clarify a few things for you. Now if you really want to create a top level camera system you can also check this video out. Its an example of how to make a third person camera with the Cinemachine component (comes with Unity package manager for free)

I wish you luck with coding in Unity and welcome to the community :)

answered Aug 29, 2019 at 5:29

mihoci10's user avatar

mihoci10mihoci10

4293 silver badges16 bronze badges

2

So, I have built a script in unity in c# called parralax. It basically parallaxes two backgrounds and looks like this:-

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parralax : MonoBehaviour {

    public float startPos;
    public GameObject cam;
    public float parallaxEffect;

    public float length;
    public GameObject player;
    public float playerStartPos;
    public float maxDisplacement;
    void Start () {
        maxDisplacement = 0f;
        playerStartPos = player.transform.position.x;
        startPos = transform.position.x;
        cam = GameObject.Find ("Main Camera");
        length = GetComponent <SpriteRenderer> ().bounds.size.x;
    }


    void Update () {

        float dist = cam.transform.position.x * parallaxEffect;
        transform.position = new Vector2 (startPos + dist, transform.position.y);

    }
}

If I put it in respective background and assign a value to it, it works fine and runs smoothly. But, if I play the game scene-wise i.e. 1st scene to 2nd scene to 3rd scene; it crashes and says:-

Unassigned reference exception:- You need to set variable cam in inspector

Even though, it runs on the same scene, it doesn’t run after I play it scene- wise. Please help!

Unassigned Reference Exception

I’m trying to make a projectile explode in my project. My error is «UnassignedReferenceException: The variable explosion of projectile has not been assigned».

Here is my code:

public Rigidbody ProjectileRigidbody; public Transform ProjectileTransform; public GameObject explosion;

// Use this for initialization
void Start()
{
    explosion.SetActive(false);

}



// Update is called once per frame

void OnTriggerEnter(Collider other)
{
    if (other.tag == "Player")
    {
        Destroy(gameObject);
        explosion.SetActive(true);
        ProjectileRigidbody = other.GetComponent<Rigidbody>();
        ProjectileRigidbody.AddForce(transform.up * 5000);
    }
    else {
        Destroy(gameObject, 5f);
    }
}

}

Where do I fix this?

The syntax error this time is : “UnassignedReferenceException : The variable XYZ of ABC.csharp has not been assigned”

This error says that you have declared a variable and used is as a GameObject, but no GameObject in the Scene has been assigned to the variable.

public GameObject camera;
 void Start () {
 camera.gameObject.SetActive(true);
 }

Therefore, you have to assign the variable camera, for example, to an object which is tagged in the Inspector. Let us say that the Object Main Camera in the Hierarchy is labelled as MainCamera in the Tag field, to assign the variable camera to the Object Main Camera, the code should be written as follow :-

public GameObject camera;
 void Start () {
 camera = GameObject.FindGameObjectWithTag("MainCamera");
 camera.gameObject.SetActive(true);
 }

Понравилась статья? Поделить с друзьями:
  • Unark dll вернул код ошибки 14
  • Unarch dll вернул код ошибки 12
  • Unarc dll ошибка при установке игры как исправить
  • Unarc dll ошибка при установке гта 5
  • Unarc dll исправляем ошибки при установке игр