Anonymous
Почему в Unity возникает ошибка NullReferenceException: ссылка на объект не установлена на экземпляр объекта в CameraS
Сообщение
Anonymous » 13 ноя 2024, 19:10
Ошибка началась после того, как я удалил из иерархии AIThirdPersonController.
Теперь у меня есть основная камера и ThirdPersonController.
У меня есть основная камера в Инспекторе i добавлен файл Camera Script.cs
Код: Выделить всё
using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
public Transform TargetLookAt;
public float Distance = 5.0f;
public float DistanceMin = 3.0f;
public float DistanceMax = 10.0f;
private float mouseX = 0.0f;
private float mouseY = 0.0f;
private float startingDistance = 0.0f;
private float desiredDistance = 0.0f;
public float X_MouseSensitivity = 5.0f;
public float Y_MouseSensitivity = 5.0f;
public float MouseWheelSensitivity = 5.0f;
public float Y_MinLimit = -40.0f;
public float Y_MaxLimit = 80.0f;
public float DistanceSmooth = 0.05f;
private float velocityDistance = 0.0f;
private Vector3 desiredPosition = Vector3.zero;
public float X_Smooth = 0.05f;
public float Y_Smooth = 0.1f;
private float velX = 0.0f;
private float velY = 0.0f;
private float velZ = 0.0f;
private Vector3 position = Vector3.zero;
CursorLockMode wantedMode;
void Start (){
Distance = Mathf.Clamp(Distance, DistanceMin, DistanceMax);
startingDistance = Distance;
Reset();
SetCursorState();
OnGUI();
}
void Update(){
}
void FixedUpdate (){
if (TargetLookAt == null)
return;
HandlePlayerInput();
CalculateDesiredPosition();
UpdatePosition();
}
void HandlePlayerInput (){
float deadZone= 0.01f; // mousewheel deadZone
//if (Input.GetMouseButton(1))
//{
mouseX += Input.GetAxis("Mouse X") * X_MouseSensitivity;
mouseY -= Input.GetAxis("Mouse Y") * Y_MouseSensitivity;
//}
// this is where the mouseY is limited - Helper script
mouseY = ClampAngle(mouseY, Y_MinLimit, Y_MaxLimit);
// get Mouse Wheel Input
if (Input.GetAxis("Mouse ScrollWheel") < -deadZone || Input.GetAxis("Mouse ScrollWheel") > deadZone)
{
desiredDistance = Mathf.Clamp(Distance - (Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity),
DistanceMin, DistanceMax);
}
}
void CalculateDesiredPosition (){
// Evaluate distance
Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velocityDistance, DistanceSmooth);
// Calculate desired position -> Note : mouse inputs reversed to align to WorldSpace Axis
desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
}
Vector3 CalculatePosition ( float rotationX , float rotationY , float distance ){
Vector3 direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0);
return TargetLookAt.position + (rotation * direction);
}
void UpdatePosition (){
float posX= Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth);
float posY= Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth);
float posZ= Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth);
position = new Vector3(posX, posY, posZ);
transform.position = position;
transform.LookAt(TargetLookAt);
}
void Reset (){
mouseX = 0;
mouseY = 10;
Distance = startingDistance;
desiredDistance = Distance;
}
float ClampAngle ( float angle , float min , float max ){
while (angle < -360 || angle > 360)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
}
return Mathf.Clamp(angle, min, max);
}
// Apply requested cursor state
void SetCursorState ()
{
Cursor.lockState = wantedMode;
// Hide cursor when locking
Cursor.visible = (CursorLockMode.Locked != wantedMode);
}
void OnGUI ()
{
GUILayout.BeginVertical ();
// Release cursor on escape keypress
if (Input.GetKeyDown (KeyCode.Escape))
Cursor.lockState = wantedMode = CursorLockMode.None;
switch (Cursor.lockState) {
case CursorLockMode.None:
GUILayout.Label ("Cursor is normal");
if (GUILayout.Button ("Lock cursor"))
wantedMode = CursorLockMode.Locked;
if (GUILayout.Button ("Confine cursor"))
wantedMode = CursorLockMode.Confined;
break;
case CursorLockMode.Confined:
GUILayout.Label ("Cursor is confined");
if (GUILayout.Button ("Lock cursor"))
wantedMode = CursorLockMode.Locked;
if (GUILayout.Button ("Release cursor"))
wantedMode = CursorLockMode.None;
break;
case CursorLockMode.Locked:
GUILayout.Label ("Cursor is locked");
if (GUILayout.Button ("Unlock cursor"))
wantedMode = CursorLockMode.None;
if (GUILayout.Button ("Confine cursor"))
wantedMode = CursorLockMode.Confined;
break;
}
GUILayout.EndVertical ();
SetCursorState ();
}
}
Ошибка в строке:
Я получаю сообщение об ошибке:
Код: Выделить всё
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUILayoutUtility.BeginLayoutGroup (UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options, System.Type layoutType) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayoutUtility.cs:252)
UnityEngine.GUILayout.BeginVertical (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayout.cs:308)
UnityEngine.GUILayout.BeginVertical (UnityEngine.GUILayoutOption[] options) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayout.cs:296)
CameraScript.OnGUI () (at Assets/My Scripts/CameraScript.cs:135)
CameraScript.Start () (at Assets/My Scripts/CameraScript.cs:43)
В Инспекторе основной камеры в области «Сценарий камеры» для параметра «Целевой взгляд» установлено значение ThirdPersonController.
Подробнее здесь:
https://stackoverflow.com/questions/385 ... t-set-to-a
1731514202
Anonymous
Ошибка началась после того, как я удалил из иерархии AIThirdPersonController. Теперь у меня есть основная камера и ThirdPersonController. У меня есть основная камера в Инспекторе i добавлен файл Camera Script.cs [code]using UnityEngine; using System.Collections; public class CameraScript : MonoBehaviour { public Transform TargetLookAt; public float Distance = 5.0f; public float DistanceMin = 3.0f; public float DistanceMax = 10.0f; private float mouseX = 0.0f; private float mouseY = 0.0f; private float startingDistance = 0.0f; private float desiredDistance = 0.0f; public float X_MouseSensitivity = 5.0f; public float Y_MouseSensitivity = 5.0f; public float MouseWheelSensitivity = 5.0f; public float Y_MinLimit = -40.0f; public float Y_MaxLimit = 80.0f; public float DistanceSmooth = 0.05f; private float velocityDistance = 0.0f; private Vector3 desiredPosition = Vector3.zero; public float X_Smooth = 0.05f; public float Y_Smooth = 0.1f; private float velX = 0.0f; private float velY = 0.0f; private float velZ = 0.0f; private Vector3 position = Vector3.zero; CursorLockMode wantedMode; void Start (){ Distance = Mathf.Clamp(Distance, DistanceMin, DistanceMax); startingDistance = Distance; Reset(); SetCursorState(); OnGUI(); } void Update(){ } void FixedUpdate (){ if (TargetLookAt == null) return; HandlePlayerInput(); CalculateDesiredPosition(); UpdatePosition(); } void HandlePlayerInput (){ float deadZone= 0.01f; // mousewheel deadZone //if (Input.GetMouseButton(1)) //{ mouseX += Input.GetAxis("Mouse X") * X_MouseSensitivity; mouseY -= Input.GetAxis("Mouse Y") * Y_MouseSensitivity; //} // this is where the mouseY is limited - Helper script mouseY = ClampAngle(mouseY, Y_MinLimit, Y_MaxLimit); // get Mouse Wheel Input if (Input.GetAxis("Mouse ScrollWheel") < -deadZone || Input.GetAxis("Mouse ScrollWheel") > deadZone) { desiredDistance = Mathf.Clamp(Distance - (Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity), DistanceMin, DistanceMax); } } void CalculateDesiredPosition (){ // Evaluate distance Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velocityDistance, DistanceSmooth); // Calculate desired position -> Note : mouse inputs reversed to align to WorldSpace Axis desiredPosition = CalculatePosition(mouseY, mouseX, Distance); } Vector3 CalculatePosition ( float rotationX , float rotationY , float distance ){ Vector3 direction = new Vector3(0, 0, -distance); Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0); return TargetLookAt.position + (rotation * direction); } void UpdatePosition (){ float posX= Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth); float posY= Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth); float posZ= Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth); position = new Vector3(posX, posY, posZ); transform.position = position; transform.LookAt(TargetLookAt); } void Reset (){ mouseX = 0; mouseY = 10; Distance = startingDistance; desiredDistance = Distance; } float ClampAngle ( float angle , float min , float max ){ while (angle < -360 || angle > 360) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; } return Mathf.Clamp(angle, min, max); } // Apply requested cursor state void SetCursorState () { Cursor.lockState = wantedMode; // Hide cursor when locking Cursor.visible = (CursorLockMode.Locked != wantedMode); } void OnGUI () { GUILayout.BeginVertical (); // Release cursor on escape keypress if (Input.GetKeyDown (KeyCode.Escape)) Cursor.lockState = wantedMode = CursorLockMode.None; switch (Cursor.lockState) { case CursorLockMode.None: GUILayout.Label ("Cursor is normal"); if (GUILayout.Button ("Lock cursor")) wantedMode = CursorLockMode.Locked; if (GUILayout.Button ("Confine cursor")) wantedMode = CursorLockMode.Confined; break; case CursorLockMode.Confined: GUILayout.Label ("Cursor is confined"); if (GUILayout.Button ("Lock cursor")) wantedMode = CursorLockMode.Locked; if (GUILayout.Button ("Release cursor")) wantedMode = CursorLockMode.None; break; case CursorLockMode.Locked: GUILayout.Label ("Cursor is locked"); if (GUILayout.Button ("Unlock cursor")) wantedMode = CursorLockMode.None; if (GUILayout.Button ("Confine cursor")) wantedMode = CursorLockMode.Confined; break; } GUILayout.EndVertical (); SetCursorState (); } } [/code] Ошибка в строке: [code]GUILayout.BeginVertical (); [/code] Я получаю сообщение об ошибке: [code]NullReferenceException: Object reference not set to an instance of an object UnityEngine.GUILayoutUtility.BeginLayoutGroup (UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options, System.Type layoutType) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayoutUtility.cs:252) UnityEngine.GUILayout.BeginVertical (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayout.cs:308) UnityEngine.GUILayout.BeginVertical (UnityEngine.GUILayoutOption[] options) (at C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayout.cs:296) CameraScript.OnGUI () (at Assets/My Scripts/CameraScript.cs:135) CameraScript.Start () (at Assets/My Scripts/CameraScript.cs:43) [/code] В Инспекторе основной камеры в области «Сценарий камеры» для параметра «Целевой взгляд» установлено значение ThirdPersonController. Подробнее здесь: [url]https://stackoverflow.com/questions/38542012/in-unity-why-getting-error-nullreferenceexception-object-reference-not-set-to-a[/url]