Using C# in Unity: Tutorials I used
- by Prasanna Kulkarni
- October 31
- in
You can control the behavior of your characters in Unity using JavaScript(JS) or C#. Though JS is an easier language and a lot of people know it, from my initial research I concluded that C# trumps JS when it comes to scripting on Unity. I added a custom controller to control my character in Unity and added a C# script to define the behavior of the character when keys on keyboard are pressed.
I achieved this by following two tutorials:
I followed only half of this tutorial to learn how to create custom controllers, assign it to a character, and add states in Mecanim
- https://teamtreehouse.com/library/how-to-make-a-video-game (I would recommend this tutorial)
Used it to know more about C# (Note: this was my first encounter with C#).
Following are the steps I took in my project:
- Added a custom controller to my player using Animator component on the player
- Added a C# script to the player
- Added a state to the player controller; other than 'Entry' and added to animations to the state using BlenTree; Idle and Walking
- Added the following code to the C# script that we assigned to the player earlier. There was a lot of trial and error to make the code work:
using UnityEngine;
using System.Collections;
public class ShivaControllerScript : MonoBehaviour {
private Animator myAnimator;
private float moveHorizontal;
private float moveVertical;
private Vector3 movement;
private float turningSpeed = 20f;
private Rigidbody playerRigidbody;
// Use this for initialization
void Start () {
myAnimator = GetComponent ();
playerRigidbody = GetComponent ();
//playerRigidbody = GetComponent ();
}
// Update is called once per frame
void Update () {
moveHorizontal = Input.GetAxisRaw ("Horizontal");
moveVertical = Input.GetAxisRaw ("Vertical");
movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
//myAnimator.SetFloat ("Speed", Input.GetAxis("Vertical"));
}
void FixedUpdate () {
if (movement != Vector3.zero) {
Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);
Quaternion newRotation = Quaternion.Lerp (playerRigidbody.rotation, targetRotation, turningSpeed * Time.deltaTime);
playerRigidbody.MoveRotation(newRotation);
myAnimator.SetFloat ("Speed", 60f);
//myAnimator.SetFloat ("Speed", Input.GetAxisRaw("Vertical"));
} else {
myAnimator.SetFloat ("Speed", 0f);
//myAnimator.SetFloat ("Speed", Input.GetAxisRaw("Vertical"));
}
}
}
COMMENTS