Assets\EndTriger.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations - c#

So i made a starter game from brackeys and i get 3 errors please help me
Script:GameManager
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public bool gameHasEnded = false;
public float restartDelay = 1f;
public void CompleteLevel ()
{
Debug.Log("LEVEL COMPLETE");
}
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
script:EndTriger
using UnityEngine;
public class EndTriger : MonoBehaviour
public GameManager gameManager;
{
void OnTriggerEnter()
{
gameManager.CompleteLevel();
}
}

EndTriger:
using UnityEngine;
public class EndTriger : MonoBehaviour
{
public GameManager gameManager;
void OnTriggerEnter()
{
gameManager.CompleteLevel();
}
}

Related

Executing a Function Between Script Files

Tell me please. I have 2 scripts that hang on different Unity objects. The first script is for clicking a button. The second one is for executing the function.
How can I execute the AddItem function if the button is pressed?
Script 1 (button click):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class UseButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public bool isClick = false;
public void OnPointerDown(PointerEventData ped)
{
isClick = true;
}
public void OnPointerUp(PointerEventData ped)
{
isClick = false;
}
}
Script 2 (Adding Items):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class InventoryManager : MonoBehaviour
{
public void AddItem(ItemScriptableObject _item, int _amount)
{
foreach(InventorySlot slot in slots)
{
if (slot.item == _item)
{
slot.amount += _amount;
return;
}
}
foreach(InventorySlot slot in slots)
{
//print(_item+" "+_amount);
if (slot.isEmpty == true)
{
slot.item = _item;
slot.amount = _amount;
slot.isEmpty = false;
slot.SetIcon(_item.icon);
return;
}
}
}
If you dont have a variable on the second script, of the first script, you should do that by using:
GameObject go;
go.GetComponent<InventoryManager>();
try changing the first script to something like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class UseButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public bool isClick = false;
void Update()
{
if (isClick)
{
Debug.Log("do something")
}
}
public void OnPointerDown(PointerEventData ped)
{
isClick = true;
}
public void OnPointerUp(PointerEventData ped)
{
isClick = false;
}
}
This way you can modify the variable: is Click easily.

OnCollisionEnter() not working when two GameObjects collide

This code here doesn't work, I don't get any errors, but the scripts doesn't print "End" in the console when my player hits something, here's the code:
using UnityEngine;
public class GameManager : MonoBehaviour
{
public void End(){
Debug.Log("End");
}
}
and on another script:
using UnityEngine;
public class PlayerCollision3 : MonoBehaviour
{
public Move movement;
void OnCollisionEnter (Collision collisionInfo) {
if (collisionInfo.collider.tag == "obsik"){
movement.enabled = false;
FindObjectOfType<GameManager>().End();
}
}
}

Event Action Doesn't work in state Pattern

I'm using state pattern for my unity game. I have three states; HappyState, SurprisedState and SadState. HappyState is default state. I want the character to jump and enter surprised state by clicking left-mouse. Entering surprised state, a few jobs need to be done which I defined as a void to be subscribed to an event, But it doesn't work!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class CapsuleScript : MonoBehaviour
{
public event Action SliderAction;
public Slider slider;
public Text stateText;
public GameObject hands;
public Rigidbody rb;
public CapsuleBasicStates currentstate;
public readonly HappyState happyState = new HappyState();
public readonly SadState sadState = new SadState();
public readonly SurprisedState surprisedState = new SurprisedState();
public SpriteRenderer renderer;
public Sprite happysprite, sadsprite, surprisedsprite;
// Start is called before the first frame update
void Start()
{
slider.value = 0;
renderer = GetComponentInChildren<SpriteRenderer>();
rb = GetComponent<Rigidbody>();
TransitionToState(happyState);
}
public void OnCollisionEnter(Collision other) {
currentstate.OnCollisionEnter(this);
}
// Update is called once per frame
void Update()
{
currentstate.Update(this);
}
public void SetSprite(Sprite sprite)
{
renderer.sprite = sprite;
}
public void TransitionToState(CapsuleBasicStates state)
{
currentstate = state;
currentstate.EnterState(this);
}
public IEnumerator SliderHandler()
{
yield return new WaitForSeconds(1f);
slider.value +=1;
StartCoroutine(SliderHandler());
}
public void IEHandler()
{
StartCoroutine(SliderHandler());
}
}
Here is SurprisedState script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SurprisedState : CapsuleBasicStates
{
public override void EnterState(CapsuleScript player)
{
player.SetSprite(player.surprisedsprite);
player.stateText.text = player.surprisedState.ToString();
player.slider.gameObject.SetActive(true);
player.SliderAction += player.IEHandler;
}
public override void OnCollisionEnter(CapsuleScript player)
{
//player.TransitionToState(player.happyState);
}
public override void Update(CapsuleScript player)
{
if(player.slider.value ==20)
{
player.SliderAction -= player.IEHandler;
player.TransitionToState(player.happyState);
}
}
}
HappyState script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HappyState : CapsuleBasicStates
{
public override void EnterState(CapsuleScript player)
{
player.SetSprite(player.happysprite);
player.stateText.text = player.happyState.ToString();
player.hands.SetActive(false);
}
public override void OnCollisionEnter(CapsuleScript player)
{
}
public override void Update(CapsuleScript player)
{
if(Input.GetButton("Fire1"))
{
player.rb.AddForce(Vector3.up * 150f);
player.TransitionToState(player.surprisedState);
}
if(Input.GetButton("Fire2"))
{
player.rb.AddForce(Vector3.up *250f);
player.TransitionToState(player.sadState);
}
}
}
Few points before I post my solution:
Try to post all scripts related to the question you are asking.
Comment your code or try to explain what each part of your script is doing.
BaseSate.cs
[System.Serializable]
public abstract class BaseState
{
public enum PlayerStates { HappyState = 0, SurprisedState = 1 }
public abstract PlayerStates PlayerState { get; }
public abstract void EnterState(PlayerScript playerScript);
public abstract void UpdateState();
public abstract void ExitState();
}
HappySate.cs
using UnityEngine;
[System.Serializable]
public class HappyState : BaseState
{
public override PlayerStates PlayerState => PlayerStates.HappyState;
private PlayerScript _playerScript;
public override void EnterState(PlayerScript playerScript)
{
_playerScript = playerScript;
Debug.Log($"Entered {PlayerState}");
}
public override void UpdateState()
{
if (Input.GetButtonDown("Fire1"))
{
_playerScript.ChangeState(new SurprisedState());
}
}
public override void ExitState()
{
Debug.Log($"Exited {PlayerState}");
}
}
SurprisedState.cs
using UnityEngine;
[System.Serializable]
public class SurprisedState : BaseState
{
public override PlayerStates PlayerState => PlayerStates.SurprisedState;
private PlayerScript _playerScript;
public override void EnterState(PlayerScript playerScript)
{
_playerScript = playerScript;
// subscribe to sliderAction on enter
playerScript.playerSliderAction += OnSliderChange;
Debug.Log($"Entered {PlayerState}");
}
private void OnSliderChange(float sliderValue)
{
// use Mathf.Approximately instead of == when comparing
// floating numbers.
if (Mathf.Approximately(sliderValue, 20f))
{
_playerScript.ChangeState(new HappyState());
}
}
public override void UpdateState() { }
public override void ExitState()
{
// unSubscribe to sliderAction on exit
_playerScript.playerSliderAction -= OnSliderChange;
Debug.Log($"Exited {PlayerState}");
}
}
PlayerScript.cs
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class PlayerScript : MonoBehaviour
{
[SerializeField]
private SpriteRenderer playerRenderer;
[SerializeField]
private Sprite[] playerStateSprites;
[SerializeField]
private Slider playerSlider;
public UnityAction<float> playerSliderAction;
private BaseState _currentState;
private void Awake()
{
Initialize();
}
private void Update()
{
_currentState.UpdateState();
}
private void Initialize()
{
ChangeState(new HappyState());
// use slider onValueChanged instead of checking slider
// value every frame.
// invoke unity action when the value has been changed.
playerSlider.onValueChanged.AddListener(sliderValue =>
{
playerSliderAction?.Invoke(sliderValue);
});
}
public void ChangeState(BaseState newState)
{
// change state only when it is different
// from previous state.
if (_currentState == newState)
{
return;
}
_currentState?.ExitState();
_currentState = newState;
_currentState.EnterState(this);
playerRenderer.sprite = playerStateSprites[(int)newState.PlayerState];
Debug.Log($"Current State : {_currentState.PlayerState}");
}
}
PlayerScript inspector view
Execution Overview gif:
https://gfycat.com/grimflowerycollardlizard

How to enable/disable scripts in 1 gameObject?

I have gameObject MainCamera and there is script LookAtCamera as my main view option and I have script MouseLook that I wanna make secondary with right-click.
using UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour {
void Update () {
if (Input.GetKey (KeyCode.Mouse1)) {
LookAtCamera.enabled = false;
MouseLook.enabled = true;
}
}
}
How to declare script as a public component of MainCamera? I just have one of them enabled and switch between with mouse right click.
You've got most of it done. So, declare the scripts as a public variable like below, and then assign them on the inspector:
using UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour {
public LookAtCamera lookAtScript;
public MouseLook mouseLookScript;
void Update () {
if (Input.GetKey (KeyCode.Mouse1)) {
lookAtScript.enabled = false;
mouseLookScript.enabled = true;
}
}
}
Thx :) I didn't know how to declare script. I also added else to go back to default camera setup.
using UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour {
public LookAtCamera lookAtScript;
public MouseLook mouseLookScript;
void Update () {
if (Input.GetKey (KeyCode.Mouse1)) {
lookAtScript.enabled = false;
mouseLookScript.enabled = true;
} else {
mouseLookScript.enabled = false;
lookAtScript.enabled = true;
}
}
}

Changing Int from another script

I want to change the playerCurScore integer (in ScoreManager script) from HarmEnemiesScript.
(Script attached to Object in Scene)
using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public int playerScore;
public int playerCurScore;
public void Start()
{
playerScore = 0;
playerCurScore = 0;
}
public void Update()
{
playerCurScore = playerScore;
}
}
(Script attached on Enemy)
using UnityEngine;
using System.Collections;
public class HarmEnemies : MonoBehaviour
{
public float enemyHealth;
public float enemyCurHealth;
public float playerDamage;
public void Start()
{
enemyCurHealth = enemyHealth;
}
public void OnTriggerEnter(Collider theCollision)
{
if(theCollision.tag == "Fireball")
{
enemyCurHealth = enemyCurHealth - playerDamage;
Destroy (theCollision);
}
if(enemyCurHealth <= 0)
{
Destroy (this.gameObject);
}
}
}
So how can I change the playerCurScore Int from HarmEnemies. I know that I have to use GetComponent and I can use playerCurScore++;
You are making several mistakes. The main one is that the ScoreManager script should not be attached to the EnemyGameObject.
Make a separate GameObject and name it ScoreManager. Then find it in the scene and update the score.
ScoreManager s = GameObject.Find("ScoreManager");
s.SendMessage("incrementScore", amount);
In the ScoreManager class you need this:
private static int score;
public void incrementScore(int amount)
{
score += amount;
}
If you are clever you make the whole ScoreManager class static and then it wouldn't even have to be a MonoBehaviour.
You would then call it like this:
ScoreManager.incrementScore(amount);
Information about static classes.
I could fix it now, thank you for the static hint. my code looks like this now:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static float playerScore;
public Text scoreCount;
public void Update()
{
ScoreController ();
}
public void ScoreController()
{
scoreCount.text = "Score: " + playerScore;
Debug.Log ("Score: " + playerScore);
}
}
using UnityEngine;
using System.Collections;
public class HarmEnemies : MonoBehaviour
{
public float enemyHealth;
public float enemyCurHealth;
public float playerDamage;
public void Start()
{
enemyCurHealth = enemyHealth;
}
public void OnTriggerEnter(Collider theCollision)
{
if(theCollision.tag == "Fireball")
{
enemyCurHealth = enemyCurHealth - playerDamage;
Destroy (theCollision);
}
if(enemyCurHealth <= 0)
{
ScoreManager.playerScore = (ScoreManager.playerScore + 1);
Destroy (this.gameObject);
}
}
}

Categories