Hi,
I am making an fps game, and im making a scope for my sniper rifle. Im using a render texture on my scope, which is attached to a camera on the barrel of the sniper rifle, to be able to make a nice zoom effect. However, I wanted to enable the camera when i scope in, making it show the render texture, and disable it when i unscoped, making the texture go black, for performance boosts. How would i be able to do that through script (if u can through script)?
Heres my code:
using System.Collections;
using UnityEngine;
public class ScopeIn : MonoBehaviour
{
[Header("Booleans")]
public bool isScoping = false;
public bool isFiring;
public bool ableToScope = true;
public bool ableToSprint = true;
[Header("FOV and Speed Settings")]
public float transitionSpeed = 5f;
public float defaultFOV = 60f;
public float scopedFOV = 50f;
public float scopeFOV = 50f;
[Header("Position Settings")]
public Vector3 aimPosition = new Vector3(0.5f, -0.3f, 0.7f);
public Vector3 defaultPosition = new Vector3(0.5f, -0.5f, 0.8f);
[Header("Prefabs")]
public GameObject crosshair;
public Camera fpsCamera;
public GameObject gun;
public Camera scopeCam;
private Coroutine zoomCoroutine;
void Start()
{
fpsCamera.fieldOfView = defaultFOV;
gun.transform.localPosition = defaultPosition;
scopeCam.fieldOfView = scopeFOV;
}
void Update()
{
if (Input.GetButtonDown("Fire2") && ableToScope)
{
Scope(true);
GameObject.Find("ScopeCamera").GetComponent<Camera>().enabled = true;
}
if (Input.GetButtonUp("Fire2") && !isFiring && ableToScope)
{
Scope(false);
GameObject.Find("ScopeCamera").GetComponent<Camera>().enabled = false;
}
// Smoothly transition the gun position
Vector3 targetPosition = isScoping ? aimPosition : defaultPosition;
gun.transform.localPosition = Vector3.Lerp(gun.transform.localPosition, targetPosition, Time.deltaTime * transitionSpeed);
}
private void Scope(bool scoping)
{
isScoping = scoping;
ableToSprint = !scoping;
crosshair.SetActive(!scoping);
float targetFOV = scoping ? scopedFOV : defaultFOV;
if (zoomCoroutine != null)
{
StopCoroutine(zoomCoroutine);
}
zoomCoroutine = StartCoroutine(LerpFieldOfView(fpsCamera, targetFOV, 0.15f));
}
private IEnumerator LerpFieldOfView(Camera targetCamera, float toFOV, float duration)
{
float startFOV = targetCamera.fieldOfView;
float elapsedTime = 0f;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
targetCamera.fieldOfView = Mathf.Lerp(startFOV, toFOV, elapsedTime / duration);
yield return null;
}
targetCamera.fieldOfView = toFOV;
}
}
Sorry, I’m a bit of a noob so if all the code is too much, my bad.