Search Unity

Why doesn't a simple script work?

Discussion in 'Scripting' started by Ziya, Nov 4, 2016.

  1. Ziya

    Ziya

    Joined:
    Aug 30, 2013
    Posts:
    65
    I created a new project and added a simple script. It compiles, but doesn't work at runtime.
    I use C#, Microsoft Visual Studio 2015.

    I did next:
    1. GameObject/3d Object/Cube.
    2. Add Component.
    3. New Script.
    4. C Sharp.
    5. Create and Add.
    6. I copied the next script from Unity tutorial and pasted:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NewBehaviourScript : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.  
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update()
    13.     {
    14.         if (Input.GetKeyDown(KeyCode.R))
    15.         {
    16.             GetComponent<Renderer>().material.color = Color.red;
    17.         }
    18.         if (Input.GetKeyDown(KeyCode.G))
    19.         {
    20.             GetComponent<Renderer>().material.color = Color.green;
    21.         }
    22.         if (Input.GetKeyDown(KeyCode.B))
    23.         {
    24.             GetComponent<Renderer>().material.color = Color.blue;
    25.         }
    26.     }
    27. }
    28.  
    Nothing happens, when I press R, G, B.
    I checked other scripts and they don't work in the the same way.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    I copied your script, putting it into a NewBehaviourScript.cs file, attaching it to a 3D cube in the scene, pressed play and it works perfectly with R, G, B.

    Check that you didn't rename the .CS file: it has got to be the same as the classname (in this case NewBehaviourScript).

    Check that you put the script ON the actual cube. It cannot work on any other object than the one with the renderer.
     
  3. Ziya

    Ziya

    Joined:
    Aug 30, 2013
    Posts:
    65
    I found solution. It was because I didn't add material. I am a beginner.