- Home /
Error: Cannot cast from source type to destination type
Hello! I am getting an annoying bug and I can't find a way to fix it, Cannot cast from source type to destination type. I think the problem is located somewhere in the following code. If anyone knows how to fix it that would be great, thanks!
private void OnTriggerEnter(Collider LasarCollider) { Collider LaserCollider = gameObject.GetComponent(); if(LaserCollider.transform.parent.tag == "Asteroid") { print("hi"); } }
----> IN A DIFFERENT SCRIPT
if (Input.GetKey(KeyCode.Space)) { GameObject Shoot = Instantiate(LasarBeam, transform.position, transform.rotation).gameObject; }
Answer by Larry-Dietz · Dec 26, 2017 at 04:52 AM
in your OnTriggerEnter, i am confused as to the purpose of the line Collider LaserCollider = gameObject.GetComponent(); If you are trying to see if you collided with an object with a parent tag of Asteroid you shoudl just dom something like this...
private void OnTriggerEnter(Collider LasarCollider) {
if(LasarCollider.transform.parent.tag == "Asteroid")
print("hi");
}
Which line is actually throwing the error? I am assuming it is the line I mentioned wasn't needed, as you are asking it to get a component, but not specifying what type of component to get.
Hopefully this helps, -Larry
Answer by Chessnutter · Dec 26, 2017 at 04:53 AM
The line throwing the error was the 2nd part of the code I posted above. Thanks for your advice, I'll see if it works.
I replaced the code with what you provided, and unfortunately I receive the same error, from the same part of the code. Sorry :(
So if I am understanding you right, you are getting the error while instantiating the object? Not within the trigger?
Looking at your code for instantiating the object, I don't see anything that stands out. The only thing off the top of my head would be if LasarBeam was null. Is LasarBeam a prefab that you are dragging onto the script in the inspector? If so, have you confirmed that you actually drug something onto it, so it has a value?
Also, just to point it out, instantiate returns a GameObject, so you don't actually need the .gameObject at the end of your instantiate line.
Your answer
Follow this Question
Related Questions
How to move a Sphere using physics 0 Answers
Constraining maximum movement speed on a rigidbody on certain axes. 1 Answer
Objects stuck dragging across floor 1 Answer
Syntax errors? 2 Answers