Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Sveyh · Apr 02, 2014 at 02:06 PM · cameraerrortutorialmaincamera

C# camera script error

Hello, I've been following a tutorial all the steps and I think I missed something cus I'm getting a null reference error and my camera aint following my Character. It's a 3rd person character Im trying to create using UnityEngine; using System.Collections;

 public class TP_Controller : MonoBehaviour 
 {
     public static CharacterController Charactercontroller;
     public static TP_Controller Instance;
 
     void Awake () 
     {
         Charactercontroller = GetComponent ("CharacterController") as CharacterController;
         Instance = this;
         TP_Camera.UseExistingOrCreateNewMainCamera ();
     }
     void Update () 
     {
         if (Camera.mainCamera == null) 
         {
             return;
         }
         GetLocoMotionInput ();
 
         TP_Motor.Instance.UpdateMotor ();
     }
     void GetLocoMotionInput()
     {
         var deadzone = 0.1f;
 
         TP_Motor.Instance.MoveVector = Vector3.zero;
 
         if(Input.GetAxis("Vertical") > deadzone || Input.GetAxis("Vertical") < -deadzone)
             TP_Motor.Instance.MoveVector += new Vector3(0, 0, Input.GetAxis("Vertical"));
 
 
         if(Input.GetAxis("Horizontal") > deadzone || Input.GetAxis("Horizontal") < -deadzone)
             TP_Motor.Instance.MoveVector += new Vector3(Input.GetAxis("Horizontal"), 0, 0);
     }
 }


I tried going back to the tutorials and I can't find it, the problem I got now is that the camera aint following the character and if anyone could help me resolve that problem. It said I got an null reference, instance not set to an object, something like that at this line

         TP_Motor.Instance.MoveVector = Vector3.zero;


I would be greatfull if anyone could help me.

EDIT 1:

Here's the TP_Camera script:

 using UnityEngine;
 using System.Collections;
  
 public class TP_Camera : MonoBehaviour 
 {
     public static TP_Camera Instance;
     public Transform TargetLookAt;
     public float Distance = 5f;
     public float DistanceMin = 3f;
     public float DistanceMax = 10f;
     public float X_mouseSensitivity = 5f;
     public float Y_mouseSensitivity = 5f;
     public float mouseWheelSensitivity = 5f;
     public float Y_MinLimit = -40f;
     public float Y_MaxLimit = 80f;
     public float distanceSmooth = 0.05f;
     private float velDistance = 0f;
     public float X_Smooth = 0.05f;
     public float Y_Smooth = 0.1f;
  
     private float MouseX = 0f;
     private float velX = 0f;
     private float velY = 0f;
     private float velZ = 0f;
     private float MouseY = 0f;
     private float StartDistance = 0f;
     private Vector3 desiredPosistion = Vector3.zero;
     private float DesiredDistance = 0f;
     private Vector3 Posistion = Vector3.zero;
  
  
  
     void Awake()
     {
        Instance = this;
     }
  
  
     void Start() 
     {
        Distance = Mathf.Clamp (Distance, DistanceMin, DistanceMax);
        StartDistance = Distance;
        Reset ();
     }
  
     void LateUpdate() 
     {
        if (TargetLookAt == null) 
          return;
  
        HandlePlayerInput ();
        CalculateDesiredPosistion ();
        UpdatePosistion ();
  
  
     }
     void HandlePlayerInput()
     {
        var deadZone = 0.01f;
        if (Input.GetMouseButton (1)) 
        {
          MouseX += Input.GetAxis("Mouse X") * X_mouseSensitivity;
          MouseY -= Input.GetAxis("Mouse Y") * Y_mouseSensitivity;
        }
  
        MouseY = Helper.ClampAngle (MouseY, Y_MinLimit, Y_MaxLimit);
  
        if (Input.GetAxis ("Mouse ScrollWheel") < -deadZone || Input.GetAxis ("Mouse ScrollWheel") > deadZone) 
        {
          DesiredDistance = Mathf.Clamp(Distance - Input.GetAxis ("Mouse ScrollWheel") * mouseWheelSensitivity, DistanceMin, DistanceMax);
        }
  
  
  
     }
     public void Reset()
     {
        MouseX = 0;
        MouseY = 10;
        Distance = StartDistance;
        DesiredDistance = Distance;
     }
     void CalculateDesiredPosistion()
     {
        Distance = Mathf.SmoothDamp (Distance, DesiredDistance, ref velDistance, distanceSmooth);
  
        desiredPosistion = CalculatePosistion (MouseY, MouseX, Distance);
     }
     Vector3 CalculatePosistion(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 UpdatePosistion()
     {
        var posX = Mathf.SmoothDamp (Posistion.x, desiredPosistion.x, ref velX, X_Smooth);
        var posY = Mathf.SmoothDamp (Posistion.y, desiredPosistion.y, ref velY, Y_Smooth);
        var posZ = Mathf.SmoothDamp (Posistion.z, desiredPosistion.z, ref velZ, X_Smooth);
        Posistion = new Vector3 (posX, posY, posZ);
  
        transform.position = Posistion;
  
        transform.LookAt (TargetLookAt);
     }
  
  
     public static void UseExistingOrCreateNewMainCamera()
     {
        GameObject tempCamera;
        GameObject targetLookAt;
        TP_Camera myCamera;
  
        if (Camera.mainCamera != null) 
        {
          tempCamera = Camera.mainCamera.gameObject;
        } 
        else 
        {
          tempCamera = new GameObject("Main Camera");
          tempCamera.AddComponent("Camera");
          tempCamera.tag = "MainCamera";
        }
        tempCamera.AddComponent ("TP_Camera");
        myCamera = tempCamera.GetComponent ("TP_Camera") as TP_Camera;
  
        targetLookAt = GameObject.Find ("TargetLookAt") as GameObject;
  
  
        if (targetLookAt == null) 
        {
          targetLookAt = new GameObject("targetLookAt");
          targetLookAt.transform.position = Vector3.zero;
        }
        myCamera.TargetLookAt = targetLookAt.transform;
  
     }
 }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Gruffy · Apr 02, 2014 at 03:25 PM 0
Share

Okay, in all your classes, you need to change any line with this

 if (Camera.mainCamera != null) 

to this

 if (Camera.main!= null) 

as it seems you are addressing this in all your connecting classes , probably. :0 lets get that done first if okay Take care bud Gruffy

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Gruffy · Apr 02, 2014 at 02:27 PM

Hey bud, do you just want your camera to follow you third person controller?

Below is a script that will follow your player , you must attach your player game object in the inspector to it.

For best result, place an empty game object in your scene, add this script to that and child your camera to the empty game object at (0,0,0. Then in the inspector, you can fiddle with the height and rotation inc height and rotation dampening for your convenience. This will then undoubtedly follow your player.

With respect to what you were doing above, Icouldnt see that you were calling your camera at any stage or indeed changing its position based on your TP_Controller. however, I am unfamiliar with how you are doing it generally...? Are you using a Plugin package for your 3rd person controller? Is it a 3DBuzz tutorial or something?

RE, these type of calls

TP_Camera.UseExistingOrCreateNewMainCamera ();

Anyway, the below script will indeed solve your camera following problem. Perhaps you could addend your TP_Control system to reflect.

using UnityEngine;

 public class FollowCamera : MonoBehaviour 
 {
     /*
      * Class members
      */
     public Transform _target;
     public float _distance = 10.0f;
     public float _height = 1.0f;
     public float _damping = 5.0f;
     public float _rotationDamping = 10.0f;
     
     
     /*
      *  Update class function
      */
     private void FixedUpdate()
     {
         // Calculate and set camera position
         Vector3 desiredPosition = this._target.TransformPoint(0, this._height, -this._distance);
         this.transform.position = Vector3.Lerp(this.transform.position, desiredPosition, Time.deltaTime * this._damping);
         
         // Calculate and set camera rotation
         Quaternion desiredRotation = Quaternion.LookRotation(this._target.position - this.transform.position, this._target.up);
         this.transform.rotation = Quaternion.Slerp(this.transform.rotation, desiredRotation, Time.deltaTime * this._rotationDamping);
     }
 }


Take care bud, hope it helps some, if not...?! It may help us further to see your TP_Camera class to divulge whats happening when that call is fired (I.E Whether TP_camera is supposed to be doing the positoinal updates based from TP_Controller or/and TP_Motor) Gruffy

EDIT: If it is a 3DBuzz tutorial, did you set the third person controller object in the script of your Camera class?

Comment
Add comment · Show 23 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Sveyh · Apr 02, 2014 at 02:30 PM 0
Share

it was a 3D buzz tutorial, been following that one all morning and this was the only problem I got

avatar image Gruffy · Apr 02, 2014 at 02:32 PM 0
Share

okay, so you firstly need to see if you set the third person gameobject as your transform to follow in your TP_Camera class

Could you let me know if that is done bud? Gruffy :)

avatar image Gruffy · Apr 02, 2014 at 02:33 PM 0
Share

Also, have you moved forward in the videos because there might be some errata or something they forgot to code correctly that gets addressed in the next subsequent video tutorial of that series. A common thing unfortunately

avatar image Sveyh · Apr 02, 2014 at 03:21 PM 1
Share

(Updated the question with TP_Camera code)

avatar image Sveyh Sveyh · Apr 02, 2014 at 03:21 PM 0
Share

it wouldn't let me post it in a comment so I had to post it as an answer

avatar image Gruffy · Apr 02, 2014 at 04:13 PM 1
Share

Okay Sveyh, here is a package that follows that tutorial up to where you got to but with camera following the player about the place.

Holding the right mouse allows the camera orbit. perhaps, you could compare my code to yours and my scene set up also, as this may be the problem. Take care bud. Oh and if this answers your question coudl you please mark it so others can find the solution if they ever come up against the same probs etc. Cheers bud 3RDPControllerPackage

When you take this, beforehand open new Unity Project so as not to conflict with any of your current scripts/scenes etc, import the package and run the scene in the assets window Cheers again Gruffy

rb3rdpcontroller.zip (38.5 kB)
Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unity2D Camera won't display my objects 1 Answer

Error CS1502 help! 1 Answer

Occlusion Culling Issue (Walls/Objects Disappear) 0 Answers

GL.End requires material.SetPass before! Still with 5.6.0f3. Happens with a default scene. 2 Answers

Need help! It is not possible to invoke an expression of type 'UnityEngine.Vector3 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges