Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Accessing parent object camera

Discussion in 'Scripting' started by AtomicCabbage33, Nov 13, 2016.

  1. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    I need to set the clear flags of the player's camera to black when I display the sniper sight. I have written a script however it throws the exception ' The name `cam' does not exist in the current context'.

    script;

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class awpScopeIn : MonoBehaviour {
    5.  
    6.     public Texture scopeGUI;
    7.     private bool _isScoped = false;
    8.     public Color color = Color.black;
    9.        
    10.     void Start()
    11.     {
    12.         Camera cam = GetComponentInParent( typeof(Camera) ) as Camera;
    13.         cam.clearFlags = CameraClearFlags.SolidColor;
    14.     }
    15.    
    16.     void OnGUI()
    17.     {
    18.         float width = 600;
    19.         float height = 600;
    20.        
    21.         if (_isScoped) {
    22.             GUI.DrawTexture (new Rect ((Screen.width / 2) - (width/2), (Screen.height / 2) - (height/2), width, height), scopeGUI);  
    23.            
    24.         }
    25.     }
    26.    
    27.     void Update()
    28.     {
    29.         if(Input.GetButtonDown("Fire2"))
    30.         {
    31.             _isScoped = !_isScoped;
    32.             cam.backgroundColor = color;
    33.         }
    34.     }
    35. }
    36.  
     
  2. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,950
    "cam" is a local scoped variable in Start. Try something like this:
    Code (CSharp):
    1.     public Texture scopeGUI;
    2.     private bool _isScoped = false;
    3.     public Color color = Color.black;
    4.     private Camera cam;
    5.    
    6.     void Start()
    7.     {
    8.         cam = GetComponentInParent( typeof(Camera) ) as Camera;
    9.         cam.clearFlags = CameraClearFlags.SolidColor;
    10.     }
     
  3. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    This threw no exceptions although the camera's clear flags didn't change?