-1

Hi I new coding in c# & I working on a script to enable / disable a Unity 5 gameobject clicking on another object for both actions, the first part runs ok, but in the second part to re-enable the object show me this error:

Assets/Script/Activar.cs(11,5): error CS1519: Unexpected symbol `else' in class, struct, or interface member declaration

this is the script:

using System.Collections;
using UnityEngine;

public class Activar : MonoBehaviour {
 public GameObject modify;

 void Update () {
  if (Input.GetMouseButton (0))
   modify.SetActive (false);
 }
         else {
   modify.SetActive (true);
  }
 }
 

So what can I do to solve this? Thanks :)

Franciscø
  • 21
  • 2
  • 1
    You need to add `{` after `if (Input.GetMouseButton (0))` since there `}` after the code in that `if` statement. You are also need to add another `}` add the end because you have `{` after declaring the class but no closing pair. – Programmer Feb 15 '18 at 05:27
  • `void Update () { modify.SetActive (!Input.GetMouseButton (0)); }` – Stephen Kennedy Feb 17 '18 at 14:26

2 Answers2

5

The bracket after modify.SetActive (false); line is the end bracket of Update function. So your else statement is outside of Update function.

if (Input.GetMouseButton (0))
            modify.SetActive (false);

This is a closed if statement.

This is how it should be

using System.Collections;
using UnityEngine;

    public class Activar : MonoBehaviour {
        public GameObject modify;

        void Update () {
            if (Input.GetMouseButton (0))
                modify.SetActive (false);
            else 
                modify.SetActive (true);
        }
    }
mcelik
  • 1,073
  • 2
  • 12
  • 22
  • Ok, the error has disappearing now, but my principal idea was disappear the object with a click on another object, like a button & reappear with the click on the same button again. Now the object disappear & reappear immediately with this script, How can I solved this? Thanks again :P – Franciscø Feb 15 '18 at 21:09
  • You have to add a button to your scene. Unity will add other necessary objects when you add a button to scene by selecting GameObject->UI ->Button.On Inspector window the object has a button component which has a OnClick event list. You simply click the plus button below the component and choose your "Activar" script . Then select the function from that script which will run when you click the mouse button.Your function will not be an Update function it will be public void function that simply calls "modify.SetActive (state);" function. – mcelik Feb 16 '18 at 05:52
  • Thank you so much to all !!! I solve this with your suggestions, this lines change everythig: if (Input.GetMouseButton (0)) modify.SetActive (!modify.activeInHierarchy); – Franciscø Feb 17 '18 at 19:39
0
Input.GetMouseButtonDown(0);

I believe that's the proper call to the left mouse key. Perhaps that is why your code isn't working?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Tim Duval
  • 61
  • 12