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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Execute code when key pressed?

Discussion in 'Scripting' started by Aldebaraan, Jun 21, 2020.

  1. Aldebaraan

    Aldebaraan

    Joined:
    Jun 21, 2020
    Posts:
    6
    Code (CSharp):
    1.         public void OnLevelWasInitialized(int level)
    2.         {
    3.             ////(check for maker scene)
    4.             var sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
    5.             if (sceneName == "CustomScene")
    6.             {
    7.                 var newObject = new GameObject();
    8.                 newObject.AddComponent(Randomizer.Main.RandomizeAll);
    9.             }
    10.         }
    11.  
    12.         public class RandomizeAll
    13.         {
    14.             //public CharFemale female;
    15.             public CharFemale female = FindObjectOfType<CharFemale>();
    16.             public void Update()
    17.             {
    18.                 if (Input.GetKeyDown(KeyCode.Keypad1))
    19.                 {
    20.                     female.customInfo.shapeValueBody[0] = UnityEngine.Random.Range(0.6f, 0.95f);
    21.                     female.customInfo.shapeValueBody[1] = UnityEngine.Random.Range(0.6f, 0.9f);
    22.                 }
    23.             }
    24.         }    
    I'm trying to make the code in class RandomizeAll execute whenever i press the numpad 1 key in a particular scene.

    I was told that i needed to add the RandomizeAll class to a GameObject using AddComponent but all i'm getting is error CS0119 in visual studio.

    RandomizeAll is inside another file btw.

    Randomizer.cs => namespace Randomizer => class Main => class RandomizeAllr => class Main => class RandomizeAll

    Game that i`m editing uses unity 5.
     
  2. MatrixQ

    MatrixQ

    Joined:
    May 16, 2020
    Posts:
    87
    To be able to add a script to a gameobject, it needs to be derived from Monobehavior.
     
    Aldebaraan likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Adding to what @MatrixQ says above, it also has to be in its own file and named precisely like the classname.
     
    Aldebaraan likes this.
  4. Aldebaraan

    Aldebaraan

    Joined:
    Jun 21, 2020
    Posts:
    6
    Thanks that worked.