Hi, I’m a beginner and I’m making a top down shooter game but I can’t acces the theGun variable in the editor. Here is the code:
PlayerController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movements : MonoBehaviour
{
public float moveSpeed;
private Rigidbody myRigidbody;
private Vector3 moveInput;
private Vector3 moveVelocity;
private Camera mainCamera;
public GunController theGun;
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent();
mainCamera = FindObjectOfType();
}
// Update is called once per frame
void Update()
{
moveInput = new Vector3(Input.GetAxisRaw(“Horizontal”),0f,Input.GetAxisRaw(“Vertical”));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up,Vector3.zero);
float rayLength;
if(groundPlane.Raycast(cameraRay,out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook,Color.blue);
transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
}
if(Input.GetMouseButtonDown(0))
theGun.isFiring = true;
if(Input.GetMouseButtonUp(0))
theGun.isFiring = false;
}
void FixedUpdate()
{
myRigidbody.velocity = moveVelocity;
}
}
GunController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunController : MonoBehaviour
{
public bool isFiring;
public BulletController bullet;
public float bulletSpeed;
public float TimeBetweenShots;
private float shotCounter;
public Transform firePoint;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(isFiring)
{
shotCounter -= Time.deltaTime;
if(shotCounter <= 0)
{
shotCounter = TimeBetweenShots;
BulletController newBullet = Instantiate(bullet,firePoint.position,firePoint.rotation) as BulletController;
newBullet.speed = bulletSpeed;
} else {
shotCounter = 0;
}
}
}
}
BulletController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
public float speed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
To make this, I followed a tutorial: