How do I assign the main camera to a variable?

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;
		
		
	}
}

When you instantiate the gun, you already have a reference to it, so you don’t need to find it with GameObject.Find. If gunPrefab has a WeaponScript component, you can just call this on the line immedately after instantiating:

gun.GetComponent<WeaponScript>().weaponusingcamera = cam;

If cam is linked to the desired camera in the inspector, then this should work. Give it a try and let us know if it works!

You can find a reference on the camera with Camera.main.
Check the API if you want an example :slight_smile: