MaxiD -9 / 1 / 0 Регистрация: 02.05.2018 Сообщений: 79 |
||||
1 |
||||
12.08.2018, 17:04. Показов 52437. Ответов 14 Метки error, unity 3d (Все метки)
Выдаёт ошибку в unity, вот текст ошибки: UnassignedReferenceException: The variable ObjectToSpawn of ObjectSpawner has not been assigned. Вот код:
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 |
|||
Ты забыл в инспекторе назначить объект в ObjectToSpawn. кстати да.. но я уже исправиться не успел ) MaxiD
То что в кавычках нужно вписать свое, предварительно назначив Tag этому объекту, тогда по идее в инспекторе можно не добавлять вручную. И присваивание это должно быть до вызова вашего Spawn().
0 |
MaxiD -9 / 1 / 0 Регистрация: 02.05.2018 Сообщений: 79 |
||||
12.08.2018, 17:31 [ТС] |
5 |
|||
Даже когда назначаю все равно ошибка. Добавлено через 52 секунды
0 |
1 / 1 / 0 Регистрация: 30.08.2015 Сообщений: 10 |
|
12.08.2018, 17:35 |
6 |
Даже когда назначаю все равно ошибка. У себя проверил. Ошибка исчезла. Проверь еще раз, объект должен быть назначен, об этом как раз и написано в тексте ошибки «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 |
Тема закрыта я проблему решил сам! Как решил-то? Может у кого-то такая же проблема будет.
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 |
Тема закрыта я проблему решил сам! Добавлено через 17 секунд я бы руки таким поотрывал… ну решил ты проблему — скажи всем как!!!! чтож за быдлокодерская привычка
0 |
15 / 8 / 7 Регистрация: 22.02.2018 Сообщений: 85 Записей в блоге: 1 |
|
13.01.2019, 13:10 |
11 |
заскринил решение Миниатюры
1 |
2 / 2 / 0 Регистрация: 03.02.2022 Сообщений: 6 |
|
03.02.2022, 13:19 |
12 |
Эта проблема возникает, когда этот скрипт висит на более, чем одном объекте. И на одном из них не указан выделенный компонент.
2 |
634 / 458 / 204 Регистрация: 05.04.2015 Сообщений: 1,877 |
|
03.02.2022, 13:35 |
13 |
Survir,
0 |
0 / 0 / 0 Регистрация: 15.12.2019 Сообщений: 7 |
|
16.03.2023, 17:27 |
14 |
zhunshun, зато этот коммент помог как минимум одному человеку в 2023)
0 |
0 / 0 / 0 Регистрация: 20.09.2023 Сообщений: 1 |
|
Вчера, 18:32 |
15 |
Спасибо)
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
83.7k9 gold badges77 silver badges115 bronze badges
asked Aug 29, 2019 at 5:00
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
rustyBucketBayrustyBucketBay
4,3503 gold badges17 silver badges47 bronze badges
3
There are multiple things you can try to do:
- Make sure you dragged the correct object in the field (I doubt that your character object is called CameraFollow)
- 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)
- 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
mihoci10mihoci10
4293 silver badges16 bronze badges
2
An error involving a NullReferenceException
is something that new developers often encounter when working on projects in Unity. These errors occur when attempting to access object variables, or members of object variables, when the variable itself is null.
Although the cause is simple, NullReferenceException
errors can present themselves in many different ways. As a result, fixing them isn’t always as straightforward as following a standard series of steps. In this article, we will explore the various ways that a NullReferenceException
can occur in Unity, as well as how to handle these various situations.
- Why is it a
NullReferenceException
? - How do they happen (and how do we fix them)?
- Trying to access a method or property (of a null object)
- Accessing a destroyed object
- Using an unassigned public variable
- Not every variable can have a null reference
- Conclusion
1. Why is it a NullReferenceException
?
A NullReferenceException
is an error that happens when your code tries to access an object variable (also known as a reference variable) that doesn’t exist (i.e. the value of the variable is null). Do you see where the name comes from now?
Object variables are called reference variables because the data for the object is stored in a separate address from the variable itself in memory (i.e. RAM). Instead of containing the data, the object variable will instead contain the reference address of the actual object. In layman terms, this means that the variable points to the object instead of storing it, like how a mailing address points to a house.
Hence, it is possible for different variables to point to the same object, such that modifying one variable will affect the value of another. Below is a simple example that illustrates this:
GameObject a = new GameObject(); GameObject b = a; b.name = "Awesome name"; print(a.name);
Interested to find out more about reference variables? You can check out our article about reference and value types in programming. This is a concept that is not exclusive to C# or Unity programming, so you will see it a lot when you work on other programming languages as well.
2. How do they happen (and how do we fix them)?
In a nutshell, whenever you see a NullReferenceException
, this means that some object variable in your code is null (i.e. empty) for some reason. Most commonly, you will find them in situations where you are…
a. Trying to access a method or property (of a null object)
Take the following example. It is a piece of code that can be attached to a GameObject to make it behave like a projectile, making it move rightwards the moment it spawns.
using UnityEngine; public class Projectile : MonoBehaviour { Rigidbody2D rb; public float speed = 10f; void Update() { rb.velocity = transform.right * speed; } }
This is how a GameObject with the script attached will behave:
If you attach it the script to any GameObject in your Scene, however, you will get a NullReferenceException
in the highlighted line above. This is because the variable rb
has never been assigned a value, so running rb.velocity
is the same as running null.velocity
.
To rectify this, we will have to ensure that rb
is assigned before we try to access its properties. A simple way to do this for our script is to add the following:
using UnityEngine; public class Projectile : MonoBehaviour { Rigidbody2D rb; public float speed = 10f; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { rb.velocity = transform.right * speed; } }
Be aware that your GameObject will need to have a Rigidbody2D
component for this to work. Otherwise, GetComponent<Rigidbody2D>()
will return null and you will get a null reference error anyway.
Rigidbody2D
component is required for this to work.Some additional notes:
NullReferenceException
errors can occur even if you try to access methods of null objects. For example, usingrb.AddForce(transform.right * speed)
in the above example will give the same error.- When accessing properties within properties, it is possible for any object in the chain of properties to be null. For example,
Rigidbody2D
objects have asharedMaterial
property, which may or may not be null. Hence, in a line likerb.sharedMaterial.bounciness
, it is possible for eitherrb
orsharedMaterial
to be null, and either one being null will cause aNullReferenceException
.
Article continues after the advertisement:
b. Accessing a destroyed object
Sometimes, it is possible for a NullReferenceException
to occur even if you properly assign your variables before you use them. Consider the following example:
using UnityEngine; public class Shooter : MonoBehaviour { public GameObject bulletPrefab; GameObject lastBullet; void Update() { if(Input.GetKeyDown(KeyCode.Space)) { lastBullet = Instantiate(bulletPrefab, transform.position, transform.rotation); Destroy(lastBullet, 2); } if(Input.GetKeyDown(KeyCode.LeftControl)) { print(lastBullet.name); } } }
This is a script that can be attached to a GameObject so that:
- Space causes it to shoot the projectiles we made earlier, save a reference to the projectile, and destroy the new projectile after 2 seconds.
- Ctrl causes it to print out the name of the last projectile we shot.
If you press Ctrl more than 2 seconds after shooting your last projectile, you will either get a NullReferenceException
or its closely-related cousin, a MissingReferenceException
.
This is because although lastBullet
points to an object, if the object it points to gets destroyed, then the lastBullet
variable will also become null.
If you want to prevent error messages from happening in such a case, you can add a check to see if an object variable is null before using it:
using UnityEngine; public class Shooter : MonoBehaviour { public GameObject bulletPrefab; GameObject lastBullet; void Update() { if(Input.GetKeyDown(KeyCode.Space)) { lastBullet = Instantiate(bulletPrefab, transform.position, transform.rotation); Destroy(lastBullet, 2); } if(Input.GetKeyDown(KeyCode.LeftControl) && lastBullet != null) { print(lastBullet.name); } } }
Article continues after the advertisement:
c. Using an unassigned public variable
Taking the example from (2) above, we can also get a closely-related cousin of the NullReferenceException
(called the UnassignedReferenceException
) if we try to fire a bullet with an unassigned bulletPrefab
variable.
To fix these errors, the solution is simple: Make sure you assign all the public variables you plan to use! If you would like a failsafe in case you forget to assign them, you can include a check to see if the object variable you want to use is null:
using UnityEngine; public class Shooter : MonoBehaviour { public GameObject bulletPrefab; GameObject lastBullet; void Update() { if(Input.GetKeyDown(KeyCode.Space) && bulletPrefab != null) { lastBullet = Instantiate(bulletPrefab, transform.position, transform.rotation); Destroy(lastBullet, 2); } if(Input.GetKeyDown(KeyCode.LeftControl) && lastBullet != null) { print(lastBullet.name); } } }
3. Not every variable can have a null reference
In Unity, primitives (such as int
, float
and bool
) and structs are value types, not reference types. This means that variables belonging to these 2 categories are not objects and do not hold references. Hence, they cannot cause NullReferenceException
errors.
For more information on what value types are, you can check out this article:
4. Conclusion
It’s important to note that variables of reference types need to be properly initialized and assigned valid object references to avoid NullReferenceException
(and related) errors. By implementing defensive coding practices, performing null checks, and ensuring that you assign variables, you can mitigate the risk of encountering these errors.
Did we miss any potential cause (or fix) for NullReferenceException
errors? Feel free to highlight it to us in the comments below.
Article continues after the advertisement:
UNITY3D — UNASSIGNED REFERENCE EXCEPTION — STACK OVERFLOW
WebNov 2, 2021 1 Answer Sorted by: 0 You have to assign a prefab to the segmentPrefab variable before you can clone something. Just select the GameObject on which the …
From stackoverflow.com
Reviews 2
Nov 2, 2021 1 Answer Sorted by: 0 You have to assign a prefab to the segmentPrefab variable before you can clone something. Just select the GameObject on which the …»>
See details
C# — UNITY «UNASSIGNED REFERENCE EXCEPTION» — STACK …
WebAug 29, 2019 UnassignedReferenceException: The variable CameraFollowObj of CameraFollow has not been assigned. You probably need to assign the …
From stackoverflow.com
Reviews 1
Aug 29, 2019 UnassignedReferenceException: The variable CameraFollowObj of CameraFollow has not been assigned. You probably need to assign the …»>
See details
UNASSIGNED REFERENCE EXCEPTION — UNITY ANSWERS
WebUnity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the , and connect …
From answers.unity.com
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the , and connect …»>
See details
UNITY — SCRIPTING API: UNASSIGNEDREFERENCEEXCEPTION
WebUnity is the ultimate tool for video game development, architectural visualizations, and interactive media installations — publish to the web, Windows, OS X, Wii, Xbox 360, and …
From docs.unity3d.com
Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations — publish to the web, Windows, OS X, Wii, Xbox 360, and …»>
See details
UNITY ERRORS: UNASSIGNED REFERENCE — YOUTUBE
WebUnity Errors: Unassigned Reference Kiwasi Games 2.42K subscribers Subscribe 7K views 5 years ago In this video I look at the unassigned reference error, and how you …
From youtube.com
Unity Errors: Unassigned Reference Kiwasi Games 2.42K subscribers Subscribe 7K views 5 years ago In this video I look at the unassigned reference error, and how you …»>
See details
HOW TO FIX ERRORS IN UNITY: UNASSIGNED REFERENCE EXCEPTION
WebUnity how to fix errors series.So You have written another piece of code for your game. You click Play and get an UnassignedReferenceException error.What cou…
From youtube.com
Unity how to fix errors series.So You have written another piece of code for your game. You click Play and get an UnassignedReferenceException error.What cou…»>
See details
UNASSIGNEDREFERENCEEXCEPTION: ERROR? — UNITY FORUM
WebDec 29, 2022 UnassignedReferenceException: The variable missile of PlayerMovement has not been assigned. You probably need to assign the missile variable of the …
From forum.unity.com
Dec 29, 2022 UnassignedReferenceException: The variable missile of PlayerMovement has not been assigned. You probably need to assign the missile variable of the …»>
See details
UNITY — UNASSIGNED REFERENCE EXCEPTION WHEN PROCEEDING FROM …
WebOct 26, 2019 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- …
From gamedev.stackexchange.com
Oct 26, 2019 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- …»>
See details
UNASSIGNED REFERENCE EXCEPTION ERROR? — UNITY ANSWERS
WebNov 29, 2016 UnassignedReferenceException: The variable projectile of ‘Light_Spell’ has not been assigned. You probably need to assign the projectile variable of the …
From answers.unity.com
Nov 29, 2016 UnassignedReferenceException: The variable projectile of ‘Light_Spell’ has not been assigned. You probably need to assign the projectile variable of the …»>
See details
UNITY ERROR — UNASSIGNED AND NULL REFERENCE EXCEPTION — YOUTUBE
WebWe all encounter these errors before regardless that its on accident. Here is a quick fix on how to get rid of those exceptions. Make sure that all the varia…
From youtube.com
We all encounter these errors before regardless that its on accident. Here is a quick fix on how to get rid of those exceptions. Make sure that all the varia…»>
See details
UNITY — SCRIPTING API: UNASSIGNEDREFERENCEEXCEPTION
WebUnity is the ultimate tool for video game development, architectural visualizations, and interactive media installations — publish to the web, Windows, OS X, Wii, Xbox 360, and …
From docs.unity3d.com
Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations — publish to the web, Windows, OS X, Wii, Xbox 360, and …»>
See details
UNASSIGNED REFERENCE EXCEPTION UNITY — YOUTUBE
WebFix Unassigned Reference Exception Unity
From youtube.com
Fix Unassigned Reference Exception Unity«>
See details
UNASSIGNED REFERENCE EXCEPTION? — UNITY ANSWERS
WebUse Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the , and connect with loyal and enthusiastic players and …
From answers.unity.com
Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the , and connect with loyal and enthusiastic players and …»>
See details
UNITY UNASSIGNED REFERENCE EXCEPTION [ ERROR FIXED ]: THE VARIABLE …
WebUnity unassigned Reference Exception [ Error Fixed ]: The variable has not been assigned, but it has Unity unassigned Reference Exception,The variable has no…
From youtube.com
Unity unassigned Reference Exception [ Error Fixed ]: The variable has not been assigned, but it has Unity unassigned Reference Exception,The variable has no…»>
See details
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);
}