1) Question
Write a Unity C# script that allows a player to rotate left/right with A and D keys and shoot a
projectile when the Spacebar is pressed.
Solution
using UnityEngine;
public class RotateAndShoot : MonoBehaviour
{
public float rotationSpeed = 100f;
public GameObject projectile;
public Transform firePoint;
void Update()
{
float rotate = [Link]("Horizontal");
[Link]([Link] * rotate * rotationSpeed *
[Link]);
if ([Link]([Link]))
{
Instantiate(projectile, [Link],
[Link]);
}
}
}
2) Question
Write a Unity C# script that rotates a GameObject and changes its color when the user
presses the space key.
Solution
using UnityEngine;
public class RotateAndColorChange : MonoBehaviour
{
public float rotationSpeed = 100f;
private Renderer objRenderer;
void Start()
{
objRenderer = GetComponent<Renderer>();
}
void Update()
{
[Link]([Link] * rotationSpeed * [Link]);
if ([Link]([Link]))
{
[Link] = new Color([Link],
[Link], [Link]);
}
}
}
3) Question
Write a Unity C# script that makes a light flicker randomly and toggles the light on/off when
the user presses the L key.
Solution
using UnityEngine;
public class LightFlicker : MonoBehaviour
{
public Light targetLight;
public float minIntensity = 0.5f;
public float maxIntensity = 2f;
void Update()
{
if ([Link](KeyCode.L))
{
[Link] = ![Link];
}
if ([Link])
{
[Link] = [Link](minIntensity,
maxIntensity);
}
}
}
4) Question
Write a Unity C# script that moves a GameObject with arrow keys and makes it jump when
the spacebar is pressed.
Solution
using UnityEngine;
public class MoveAndJump : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
private Rigidbody rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float moveX = [Link]("Horizontal");
float moveZ = [Link]("Vertical");
Vector3 move = new Vector3(moveX, 0, moveZ);
[Link] = new Vector3(move.x * moveSpeed, [Link].y, move.z
* moveSpeed);
if ([Link]([Link]) && isGrounded)
{
[Link]([Link] * jumpForce, [Link]);
}
}
void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}
5) Question
Write a Unity C# script that makes a GameObject move forward continuously and increases
its speed when the user holds the Shift key.
Solution
using UnityEngine;
public class ForwardMovement : MonoBehaviour
{
public float normalSpeed = 5f;
public float sprintSpeed = 10f;
void Update()
{
float speed = [Link]([Link]) ? sprintSpeed :
normalSpeed;
[Link]([Link] * speed * [Link]);
}
}