"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 This:

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)

And, Here’s ProjectileDragging And Trajectory Code:


using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.Audio;

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()
        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<TrailRenderer>().enabled = false;
        clickedOn = true;
        trajectory.UpdateDots(pos, force);


    void OnMouseUp()
        GetComponent<AudioSource>().clip = throwed;
        GetComponent<TrailRenderer>().enabled = true;
        GetComponent<Rigidbody2D>().isKinematic = false;
        clickedOn = false;


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 ()
		//hide 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 *= (Transform)Instantiate(dotPrefab, transform.position, Quaternion.identity);*

dotsList*.parent = dotsParent.transform;*

dotsList .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 this 2 lines at the top by:
//pos = (tennisballPos+forcetime)-((-Physics2D.gravitytime*time)/2f);
*//but make sure to turn “pos” in ProjectileDragging.cs to Vector2 instead of Vector3 *

dotsList*.transform.position = pos;*
* timeStamp += dotSpacing;*
* }*
* }*

* public void Show ()*
* {*
* dotsParent.SetActive (true);*
* }*

* public void Hide ()*
* {*
* dotsParent.SetActive (false);*
* }*
See? The
dotsList = Instantiate (dotPrefab, transform.position, Quaternion.identity);
dotsList*.transform.position = pos; And trajectory.UpdateDots(pos, force);*
İs, Gets Error. What Should I Do In The Correct Version Of This Code? Please, Help Me And Say The Error’s Method For Me, Ok?
Message By Efe Şantay.


dotsList *= (Transform)Instantiate(dotPrefab, transform.position, Quaternion.identity);*

I think you want this instead:
dotsList = Instantiate(dotPrefab, transform.position, Quaternion.identity).transform;
// or this
dotsList = Instantiate(dotPrefab, transform.position, Quaternion.identity).GetComponent();
Since Instantiate() creates a generic Object. [Source][1]. Casting might still work, but it’s just something 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 this 2 lines at the top by:
//pos = (tennisballPos+forcetime)-((-Physics2D.gravitytime*time)/2f);
//but make sure to turn “pos” in ProjectileDragging.cs to Vector2 instead of Vector3

dotsList*.transform.position = pos;*
timeStamp += dotSpacing;
I also noticed that pos variable is a Vector2 in the ProjectileDragging class while the parameter tennisballPos in the UpdateDots() in the Trajectory class is Vector3. I think it should be able to cast, but might be worth while to make them the same type(?). AKA have tennisballPos be a Vector2 instead of Vector 3.
_*[1]: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html*_