InvalidCastException: Cannot cast from source type to destination type.
I'm having a huge issue, as a unity noob i've looked over the already completed answers but I have no idea how to apply what fixes they've found to what I'm doing.
This is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttak : MonoBehaviour {
[SerializeField]
float delayBetweenShots = 0.4f;
float timePassedSinceLast = 0f;
// Use this for initialization
void Start() {
timePassedSinceLast = delayBetweenShots;
}
// Update is called once per frame
void Update () {
Aiming();
Shooting();
}
void Aiming()
{
var objectPos = Camera.main.WorldToScreenPoint(transform.position);
var dir = Input.mousePosition - objectPos;
transform.rotation = Quaternion.Euler (new Vector3 (0, 0, Mathf.Atan2 (-dir.x, dir.y) * Mathf.Rad2Deg));
}
void Shooting()
{
if(Input.GetMouseButton(0) && timePassedSinceLast >= delayBetweenShots)
{
GameObject dagger = (GameObject)Instantiate(Resources.Load("dagger"), transform.position, transform.rotation);
timePassedSinceLast = 0f;
}
else
{
timePassedSinceLast += Time.deltaTime;
}
}
}
And this is the error
InvalidCastException: Cannot cast from source type to destination type.
PlayerAttak.Shooting () (at Assets/scripts/PlayerAttak.cs:35)
PlayerAttak.Update () (at Assets/scripts/PlayerAttak.cs:20)
Answer by Bill9009 · Jun 09, 2017 at 09:55 PM
At line 35 you are attempting to use an explicit cast, a way to convert an object of one type to another.
- Cast format: (Desired_Type) Object.
That is not working so instead remove the "(GameObject)" and at the end of the statement (before the smicolon) put " as GameObject". This is another way to convert objects.
GameObject dagger = Instantiate(Resources.Load("dagger"), transform.position, transform.rotation) as GameObject;
Answer by Ewakhine · Jan 12, 2018 at 01:19 PM
Have you try to use
Resources.Load<GameObject>
instead of
Resources.Load
?
Plus, are you sure that you're object "dagger" is a GameObject ?
Your answer
Follow this Question
Related Questions
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
Array index is out of range. 1 Answer
The name animator does not exist in the current context... Help? 1 Answer