I am trying to assign the main camera to a variable through script.
Everything I have tried has either not worked or has an error that I can’t find a way around.
I want it so that when the prefab is instantiated, the camera is assigned to the variable.
script with variable
using UnityEngine;
public class WeaponScript : MonoBehaviour {
public float weapondamage = 0f;
public float raycastrange = 0f;
public float attackrate = 0f;
public Camera weaponusingcamera; // weapon needs camera to raycast from,
public ParticleSystem Shootfx;
private float cooldown = 0f;
// Update is called once per frame
void Update(){
if (Input.GetButton("Fire1") && Time.time >= cooldown)
{
cooldown = Time.time + 1f/attackrate;
Shoot();
Shootfx.Play();
}
}
//below is irrelevant to question
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(weaponusingcamera.transform.position, weaponusingcamera.transform.forward, out hit, range ))
{
Debug.Log(hit.transform.name);
Enemy enemy = hit.transform.GetComponent<Enemy>();
if (enemy !=null)
{
enemy.Deducthp(damage);
}
}
}
}
and the script i want to make the camera assign to
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunPickup : MonoBehaviour
{
// object 1 is weapon on ground and object 2 is weapon prefab
public GameObject gunpickup;
public GameObject gunPrefab;
public GameObject box;
// below variable is parent of prefab
public GameObject emptparent; // emptparent is child of main camera
private GameObject gun;
//
public Camera cam;
void OnTriggerEnter(Collider other)
{
gunpickup.SetActive(false);
box.SetActive(false);
gun = Instantiate(gunPrefab);
gun.transform.SetParent(emptparent.transform);
// above works perfectly at creating prefab, but prefab has no camera set
//below is failed attempt at setting the camera for the variable in WeaponScript
GameObject tempObj = GameObject.Find("GunTest");// the object created by the prefab being instantiated
WeaponScript weaponScript = GetComponent<WeaponScript>();
weaponScript.weaponusingcamera = cam;
}
}