Transform.Getcomponent

using UnityEngine;
using System.Collections;

public class FadeScript : MonoBehaviour {

    public float timer = 10.0f;
	SpriteRenderer spRend = transform.GetComponent<SpriteRenderer>();
	
	Color col = spRend.color;
	
	// Use this for initialization
	public void Start () {
	
		 col.a = 1f;
	
		
	}
	
	// Update is called once per frame
	void Update () {
		
		timer = timer - Time.deltaTime;
		
		if(timer >= 0)
		{
			
		
			col.a -= 0.1f * Time.deltaTime;
		}
		
		if(timer <= 0)
		{
			timer = 0;
		
			Destroy(gameObject);
	}
   }

this is the code. my purpose is to change alpha level of the 2D sprite on the beginning of the scene. the error in the lines where i declare spRend and col

here are the two errors i get.

Please help.
Thanks in Advance :slight_smile:

You can’t call non-static methods when initializing a class field. You’re referencing an object instance in both cases. Move the initialization of those to the Start function.

To be more specific, when you’re initializing a variable at the same time you declare it, you can only use values that are known at compile time. So numbers, numeric functions, and so on.

Try this:

 public class FadeScript : MonoBehaviour 
        {
         
             public float timer = 10.0f;
             SpriteRenderer spRend; 
             
             Color col;
             
             public void Start () 
             {
             
                  spRend = transform.GetComponent<SpriteRenderer>();
                  col = spRend.color;
                  col.a = 1f;
             
                 
             }
        
        }