Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Type-casting problem...

Discussion in 'Scripting' started by BlackArcane, Apr 12, 2013.

  1. BlackArcane

    BlackArcane

    Joined:
    Jun 26, 2011
    Posts:
    119
    I need some help here. I am probably missing something but this script returns "Cannot convert UnityEngine.Component to CharacterMotorMovement. I am trying to access Unity's character controller so that I can implement sprinting to it. Here's my code:
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerSprint : MonoBehaviour
    5. {
    6.     public int sprintModifier;
    7.     private CharacterMotorMovement movement;
    8.    
    9.     void Awake()
    10.     {
    11.         movement = (CharacterMotorMovement)gameObject.GetComponent("CharacterMotorMovement");
    12.     }
    13.    
    14.     void Update()
    15.     {
    16.         while(Input.GetKeyDown(KeyCode.LeftShift))
    17.         {
    18.             movement.maxForwardSpeed = movement.maxForwardSpeed + sprintModifier;
    19.         }
    20.         movement.maxForwardSpeed = movement.maxForwardSpeed - sprintModifier;
    21.     }
    22. }
    23.  
     
  2. element_wsc

    element_wsc

    Joined:
    Jul 27, 2012
    Posts:
    522
    Code (csharp):
    1.  
    2. movement = (CharacterMotorMovement)gameObject.GetComponent<CharacterMotorMovement>();
    3.  
    4. or
    5.  
    6. movement = gameObject.GetComponent<CharacterMotorMovement>() as CharacterMotorMovement;
    7.  
    and why are you using a while loop ?
     
  3. BlackArcane

    BlackArcane

    Joined:
    Jun 26, 2011
    Posts:
    119
    Same error in both cases: The type `CharacterMotorMovement' must be convertible to `UnityEngine.Component' in order to use it as parameter `T' in the generic type or method `UnityEngine.GameObject.GetComponent<T>()'

    I am officially stumped. LOL About the while loop, would it work correctly with an if statement?
     
  4. element_wsc

    element_wsc

    Joined:
    Jul 27, 2012
    Posts:
    522
    change while(Input.GetKeyDown(KeyCode.LeftShift) to if(Input.GetKey(KeyCode.LeftShift)))
    otherwise you will create a infinite loop.

    and the problem is that there is no component called CharacterMotorMovement in the standart assets. there is only CharacterMotor
     
  5. BlackArcane

    BlackArcane

    Joined:
    Jun 26, 2011
    Posts:
    119
    Well actually there is. It is a class in the CharacterMotor file. Isn't that registered as a component?