• 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 /
  • Help Room /
avatar image
0
Question by giyasefe · Jul 11, 2022 at 06:18 PM · unity 5errorinstantiatenull reference exceptioncast

"InvalidCastException" And "NullReferenceException" Error

Hello Again,


I fixed İnstantiate error. But, İf I'm Go To Unity And Testing My Game, İt Gets 2 Errors. First Error On Start:


 InvalidCastException: Cannot cast from source type to destination type.
 Trajectory.PrepareDots () (at Assets/Scripts/Trajectory.cs:37)
 Trajectory.Start () (at Assets/Scripts/Trajectory.cs:25)


And The Last One, İf İm Touched The Tennis Ball Game Object, Game Gets Error And Error Saying T$$anonymous$$s:

 NullReferenceException: Object reference not set to an instance of an object
 Trajectory.UpdateDots (Vector3 tennisballPos, Vector2 forceApplied) (at Assets/Scripts/Trajectory.cs:58) ProjectileDragging.OnMouseDown () (at Assets/Scripts/ProjectileDragging.cs:55)
 UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)


And, Here's ProjectileDragging And Trajectory Code:


ProjectileDragging:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.SceneManagement;
 using UnityEngine.Audio;
 [RequireComponent(typeof(AudioSource))]
 
 public class ProjectileDragging : MonoBehaviour
 {
     private bool clickedOn;
     private SpringJoint2D spring;
     private Vector2 prevVelocity;
     private Ray leftCatapultToProjectile;
     private float circleRadius;
     private Transform catapult;
     private Ray rayToMouse;
     private float maxStretchSqr;
 
     public LineRenderer catapultLineFront;
     public LineRenderer catapultLineBack;
     public float maxStretch = 3.50f;
     public AudioClip throwing;
     public AudioClip throwed;
     public ProjectileDragging tennisBall;
     public Trajectory trajectory;
 
     Vector2 pos;
     Vector2 force;
 
     void Awake()
     {
         spring = GetComponent<SpringJoint2D>();
         catapult = spring.connectedBody.transform;
 
     }
 
     void Start()
     {
         LineRendererSetup();
         GetComponent<TrailRenderer>().sortingLayerName = "Foreground";
         rayToMouse = new Ray(catapult.position, Vector3.zero);
         leftCatapultToProjectile = new Ray(catapultLineFront.transform.position, Vector3.zero);
         CircleCollider2D circle = GetComponent<Collider2D>() as CircleCollider2D;
         circleRadius = circle.radius;
         maxStretchSqr = maxStretch * maxStretch;
 
     }
 
     void OnMouseDown()
     {
         GetComponent<AudioSource>().clip = throwing;
         GetComponent<AudioSource>().Play();
         GetComponent<TrailRenderer>().enabled = false;
         clickedOn = true;
         trajectory.Show();
         trajectory.UpdateDots(pos, force);
 
     }
 
     void OnMouseUp()
     {
         GetComponent<AudioSource>().clip = throwed;
         GetComponent<AudioSource>().Play();
         GetComponent<TrailRenderer>().enabled = true;
         GetComponent<Rigidbody2D>().isKinematic = false;
         clickedOn = false;
         trajectory.Hide();
 
     }


And Trajectory Code:

 using UnityEngine;
 using System.Collections;
 
 public class Trajectory : MonoBehaviour
 {
     [SerializeField] int dotsNumber;
     [SerializeField] GameObject dotsParent;
     [SerializeField] GameObject dotPrefab;
     [SerializeField] float dotSpacing;
     [SerializeField] [Range (0.01f, 0.3f)] float dotMinScale;
     [SerializeField] [Range (0.3f, 1f)] float dotMaxScale;
 
     Transform[] dotsList;
 
     Vector2 pos;
     //dot pos
     float timeStamp;
 
     //--------------------------------
     void Start ()
     {
         //$$anonymous$$de trajectory in the start
         Hide ();
         //prepare dots
         PrepareDots ();
     }
 
     void PrepareDots ()
     {
         dotsList = new Transform[dotsNumber];
         dotPrefab.transform.localScale = Vector3.one * dotMaxScale;
 
         float scale = dotMaxScale;
         float scaleFactor = scale / dotsNumber;
 
         for (int i = 0; i < dotsNumber; i++) {
             dotsList[i] = (Transform)Instantiate(dotPrefab, transform.position, Quaternion.identity);
             dotsList[i].parent = dotsParent.transform;
 
             dotsList [i].localScale = Vector3.one * scale;
             if (scale > dotMinScale)
                 scale -= scaleFactor;
         }
     }
 
     public void UpdateDots (Vector3 tennisballPos, Vector2 forceApplied)
     {
         timeStamp = dotSpacing;
         for (int i = 0; i < dotsNumber; i++) {
             pos.x = (tennisballPos.x + forceApplied.x * timeStamp);
             pos.y = (tennisballPos.y + forceApplied.y * timeStamp) - (Physics2D.gravity.magnitude * timeStamp * timeStamp) / 2f;
 
             //you can simlify t$$anonymous$$s 2 lines at the top by:
             //pos = (tennisballPos+force*time)-((-Physics2D.gravity*time*time)/2f);
             //
             //but make sure to turn "pos" in ProjectileDragging.cs to Vector2 instead of Vector3    
 
             dotsList[i].transform.position = pos;
             timeStamp += dotSpacing;
         }
     }
 
     public void Show ()
     {
         dotsParent.SetActive (true);
     }
 
     public void Hide ()
     {
         dotsParent.SetActive (false);
     }
 }


See? The

 dotsList [i] = Instantiate (dotPrefab, transform.position, Quaternion.identity);
 dotsList[i].transform.position = pos; And  trajectory.UpdateDots(pos, force);

İs, Gets Error. What Should I Do In The Correct Version Of T$$anonymous$$s Code? Please, Help Me And Say The Error's Method For Me, Ok?


Message By Efe Şantay.

Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by MuffinMan64 · Jul 11, 2022 at 06:50 PM

For

 dotsList[i] = (Transform)Instantiate(dotPrefab, transform.position, Quaternion.identity);

I t$$anonymous$$nk you want t$$anonymous$$s instead:

 dotsList[i] = Instantiate(dotPrefab, transform.position, Quaternion.identity).transform;
 // or t$$anonymous$$s
 dotsList[i] = Instantiate(dotPrefab, transform.position, Quaternion.identity).GetComponent<Transform>();

Since Instantiate() creates a generic Object. Source. Casting might still work, but it's just somet$$anonymous$$ng I noticed.

And for in onMouseDown()

 trajectory.UpdateDots(pos, force);

I don't see how you set pos or force variables so those values will be null. Not sure how you would set them but they need to be set in order to use them!

In your UpdateDots() method could have checks to log /prevent issue:

 public void UpdateDots (Vector3 tennisballPos, Vector2 forceApplied)
      {
          // or simply: if(!tennisballPos || !forceApplied)
          if(tennisballPos == null || forceApplied == null)
          {
              Debug.LogError("Arguments are not set");
              return;
          }
          
          timeStamp = dotSpacing;
          for (int i = 0; i < dotsNumber; i++) {
              pos.x = (tennisballPos.x + forceApplied.x * timeStamp);
              pos.y = (tennisballPos.y + forceApplied.y * timeStamp) - (Physics2D.gravity.magnitude * timeStamp * timeStamp) / 2f;
  
              //you can simlify t$$anonymous$$s 2 lines at the top by:
              //pos = (tennisballPos+force*time)-((-Physics2D.gravity*time*time)/2f);
              //
              //but make sure to turn "pos" in ProjectileDragging.cs to Vector2 instead of Vector3    
  
              dotsList[i].transform.position = pos;
              timeStamp += dotSpacing;
          }
      }

I also noticed that pos variable is a Vector2 in the ProjectileDragging class w$$anonymous$$le the parameter tennisballPos in the UpdateDots() in the Trajectory class is Vector3. I t$$anonymous$$nk it should be able to cast, but might be worth w$$anonymous$$le to make them the same type(?). AKA have tennisballPos be a Vector2 instead of Vector 3.

Comment
Add comment · Show 2 · 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 Eno-Khaon · Jul 11, 2022 at 07:37 PM 0
Share
avatar image giyasefe · Jul 12, 2022 at 07:36 AM 0
Share

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

300 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 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 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 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 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 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 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Instantiating Objects randomly on a sphere with a set distance radius 0 Answers

problems with mopub 0 Answers

Unspecified error during import AudioClip 2 Answers

Instantiate too many objects 0 Answers

Want to instantiate Prefab in its parent. 1 Answer


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