How do I do the check once? - c#

I have a condition that should check whether it is true or false. I did this:
void Update()
{
if (Slot.SlotBool == true)
{
score++;
Debug.Log("OK! " + score);
}
}
But I want him to check without pressing the button, and put it in Update(), but then Score was increasing every second... Is there any other way to do it?
I have 3 scripts, the first one is needed to move an object, get a starting position, etc. It looks like this:
public class DManager : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler, IPointerClickHandler
{
public static GameObject objBeingDraged;
private Vector2 startPosition;
private Transform startParent;
private CanvasGroup canvasGroup;
private Transform itemDraggerParent;
void Start()
{
canvasGroup = GetComponent<CanvasGroup>();
itemDraggerParent = GameObject.FindGameObjectWithTag("ItemDraggerParent").transform;
}
public void OnBeginDrag(PointerEventData eventData)
{
objBeingDraged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
transform.SetParent(itemDraggerParent);
canvasGroup.blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
public void OnEndDrag(PointerEventData eventData)
{
objBeingDraged = null;
canvasGroup.blocksRaycasts = true;
if (transform.parent == itemDraggerParent)
{
transform.position = startPosition;
transform.SetParent(startParent);
}
}
public void OnPointerClick(PointerEventData eventData)
{
transform.rotation *= Quaternion.Euler(0,0, -90);
}
}
The second one is needed so that when the object is released:
public class Puzzle : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData eventData)
{
if (DManager.objBeingDraged == null) return;
DManager.objBeingDraged.transform.SetParent(transform);
}
}
And the third one is needed already in order to get an object and compare the resulting object name. I could put score accruals here, but here he checks every element
int score=0;
public static bool f=false;
public void OnDrop(PointerEventData eventData)
{
if (!item)
{
item = DManager.objBeingDraged;
if (item.name== this.gameObject.name)
{
if (item.transform.rotation == this.gameObject.transform.rotation)
{
f = true;
Debug.Log(f);
score++;
Debug.Log(score);
}
}
item.transform.SetParent(transform);
item.transform.position = transform.position;
}
}
void Update()
{
if (item != null && item.transform.parent != transform)
{
item = null;
}
}
So I created another script where points are already awarded

you can add another boolean to check if the score was already incremented.
private bool incrementedBool = false;
void Update()
{
if(incrementedBool == false)
{
incrementedBool = true;
if (Slot.SlotBool == true)
{
score++;
Debug.Log("OK! " + score);
}
}
}
Then, if you want to incremente another time the score for any reason, you can reset the boolean like that :
incrementedBool = false;

Related

Adding key functionality to OnTriggerEnter

I have 2 scripts which are working almost perfectly for me.
PlayerPositionCorrection on player :
public class PlayerPositionCorrection : MonoBehaviour
{
Transform _playerTransform;
public float _xAxys;
public float _newXAxys;
private void Start()
{
_playerTransform = GetComponent<Transform>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("ChangePlayerPosition"))
{
Debug.Log("Check if Collided With : " + other.gameObject.name);
_newXAxys = other.GetComponent<PositionCorrector>()._newXAxys;
Debug.Log("New XAxys value : " + _newXAxys);
}
}
}
and PositionCorrector on object with collider :
public class PositionCorrector : MonoBehaviour
{
public float _newXAxys = 4;
public Vector3 _playerPostion;
//public int _optionNumber = 1;
[SerializeField] bool _isInTriggerZone = false;
private void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (Input.GetKeyDown("p") && other.CompareTag("Player"))
{
_playerPostion = other.transform.position;
_playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
}
}
}
I try to add to this script PositionCorrector one future when character/player collide with object AND PRESS ANY KEY (for this purpose can be 'P') then change his position. But when character collide witch object (character) don't wait for press key just immediately changing position.
And this is what I added :
private void OnTriggerEnter(Collider other)
{
if (Input.GetKeyDown("p") && other.CompareTag("Player"))
{
_playerPostion = other.transform.position;
_playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
}
}

i have a camera shake script but when i click start it directy goes off and it wont stop

i have a camera shake script but when i click start it directy goes off and it wont stop
in this script i wanted to trigger the shake effect
public class GameOver : MonoBehaviour
{
public Explosion shake;
void OnCollisionEnter2D (Collision2D coll)
{
Debug.Log("Collision!");
if (coll.gameObject.tag == "platform")
{
Destroy(gameObject);
shake.GameOver = true;
}
}
}
and this is the other script
public class Explosion : MonoBehaviour
{
public Transform cameraTransform;
private Vector3 orignalCameraPos;
public float shakeDuration;
public float shakeAmount;
private bool canShake = false;
public bool GameOver = false;
private float _shakeTimer;
void Start()
{
orignalCameraPos = cameraTransform.localPosition;
GameOver = false;
_shakeTimer = 0;
}
void Update()
{
if (GameOver = true)
{
ShakeCamera();
}
}
public void ShakeCamera()
{
_shakeTimer = shakeDuration;
StartCameraShakeEffect();
}
public void StartCameraShakeEffect()
{
if (_shakeTimer > 0)
{
cameraTransform.localPosition = orignalCameraPos + Random.insideUnitSphere * shakeAmount;
_shakeTimer -= Time.deltaTime;
}
else
{
_shakeTimer = 0f;
cameraTransform.position = orignalCameraPos;
GameOver = false;
}
}
}
if you are able to help me i would be very thankfull :)
in the statement if (GameOver = true) you are setting GameOver to true and then checking its value. I think you might have wanted to use if (GameOver == true) or if (GameOver) which will check if this variable is set to true.

I want to enable my collider again after disabling it

When my character hits the gameobject collider, an enemy will be spawned and the collider is disabled, cuz I do not want to spawn multiple enemies. When my character dies and I have to start from the beginning, the collider should be enabled again to spawn the enemy again.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerSpawner : MonoBehaviour
{
public EnemySpawn enemyspawn;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
enemyspawn.SpawnEnemy();
gameObject.GetComponent<BoxCollider2D>().enabled = false;
}
}
}
//in other class
private void SetHealth(float health)
{
var actualNextHealth = Mathf.Min(m_maxHealth, health);
m_currentHealth = actualNextHealth;
if (m_healthBar != null && m_maxHealth > 0f)
m_healthBar.SetHealth(actualNextHealth / m_maxHealth);
if (m_currentHealth <= 0f)
{
UpdateHighscore();
Die();
}
}
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
}
else {
Destroy(gameObject);
}
}
You can create a static variable in the trigger script that you assign the Collider value to it.
When an enemy is spawned it deactivates, as in your code.
public class TriggerSpawner : MonoBehaviour
{
public static Collider2D spawnCollider;
public EnemySpawn enemyspawn;
void Start() => spawnCollider.GetComponent<Collider2D>();
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
enemyspawn.SpawnEnemy();
spawnCollider.enabled = false;
}
}
}
When you die, it will reactivate.
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
TriggerSpawner.spawnCollider.enabled = true;
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
}
else {
Destroy(gameObject);
}
}
With minimal changes on your code, I'd suggest this:
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
gameObject.GetComponent<BoxCollider2D>().enabled = true; // add this line
}
else {
Destroy(gameObject);
}
}

How can I update my newDiamondText counter on my UI to go to zero?

public class BuyableItem : MonoBehaviour
{
public float PickUpRadius = 1f;
public InventoryItemData ItemData;
private SphereCollider myCollider;
private void Awake()
{
myCollider = GetComponent<SphereCollider>();
myCollider.isTrigger = true;
myCollider.radius = PickUpRadius;
}
private void OnTriggerEnter(Collider other)
{
var inventory = other.transform.GetComponent<InventoryHolder>();
if (!inventory) return;
if (inventory.InventorySystem.AddToInventory(ItemData, 1))
{
Destroy(this.gameObject);
}
}
public static void UpdateDiamondText(PlayerInventory playerInventory)
{
InventoryUI.newDiamondText.text = playerInventory.NumberOfDiamonds.ToString();
}
}
Based off of this, how would I be able to make the counter of my InventoryUI newDiamondText script reach zero when picking up an item?

Unity 2d game Player and enemy not moving

I have been following a tutorial on a unity 2d game. The player and the enemy inherit from a base class known as MovingObject. Everything in the game works fine except that the player and the enemy can't move. Here are the scripts. The movement happens in a gridlike tile system.
This is the original tutorial series. Try going over the moving object, player, and enemy tutorials.
https://www.youtube.com/playlist?list=PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F
Base MovingObject class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class MovingObject : MonoBehaviour {
public float moveTime = 0.1f;
public LayerMask blockinglayer;
private BoxCollider2D boxCollider;
private Rigidbody2D rb2D;
private float inverseMoveTime;
// Use this for initialization
protected virtual void Start () {
boxCollider = GetComponent<BoxCollider2D>();
rb2D = GetComponent<Rigidbody2D>();
inverseMoveTime = 1f / moveTime;
}
protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
{
Vector2 start = transform.position;
Vector2 end = start + new Vector2(xDir, yDir);
boxCollider.enabled = false;
hit = Physics2D.Linecast(start, end, blockinglayer);
boxCollider.enabled = true;
if (hit.transform == null)
{
StartCoroutine(SmoothMovement(end));
return true;
}
return false;
}
protected IEnumerator SmoothMovement(Vector3 end)
{
float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
while (sqrRemainingDistance > float.Epsilon)
{
Vector3 newPosition = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
rb2D.MovePosition(newPosition);
sqrRemainingDistance = (transform.position - end).sqrMagnitude;
yield return null;
}
}
protected virtual void AttemptMove<T>(int xDir, int yDir)
where T : Component
{
RaycastHit2D hit;
bool canMove= Move(xDir, yDir, out hit);
if (hit.transform == null)
{
return;
}
T hitComponent = hit.transform.GetComponent<T>();
if(!canMove && hitComponent != null)
{
OnCantMove(hitComponent);
}
}
protected abstract void OnCantMove<T>(T component)
where T : Component;
// Update is called once per frame
}
Player Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MovingObject {
public int wallDamage = 1;
public int pointsPerFood = 10;
public int pointsPerSoda = 20;
public float restartLevelDelay = 1f;
private Animator animator;
private int food;
// Use this for initialization
protected override void Start () {
animator = GetComponent<Animator>();
food = GameManager.instance.playerFoodPoints;
base.Start();
}
private void OnDisable()
{
GameManager.instance.playerFoodPoints = food;
}
// Update is called once per frame
void Update () {
if (GameManager.instance.playersTurn)
{
return;
}
int horizontal = 0;
int vertical = 0;
horizontal = (int)Input.GetAxisRaw("Horizontal");
vertical = (int)Input.GetAxisRaw("Vertical");
if (horizontal != 0)
{
vertical = 0;
}
if(horizontal!=0 || vertical != 0)
{
AttemptMove<Wall>(horizontal, vertical);
}
}
protected override void OnCantMove<T>(T component)
{
Wall hitwall = component as Wall;
hitwall.damageWall(wallDamage);
animator.SetTrigger("playerChop");
}
protected override void AttemptMove<T>(int xDir, int yDir)
{
food--;
base.AttemptMove<T>(xDir, yDir);
RaycastHit2D hit;
CheckIfGameOver();
GameManager.instance.playersTurn = false;
}
public void LoseFood(int loss)
{
animator.SetTrigger("playerHit");
food -= loss;
CheckIfGameOver();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Exit")
{
Invoke("Restart", restartLevelDelay);
enabled = false;
}
else if (other.tag == "Food")
{
food += pointsPerFood;
other.gameObject.SetActive(false);
}
else if (other.tag == "Soda")
{
food += pointsPerSoda;
other.gameObject.SetActive(false);
}
}
private void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void CheckIfGameOver()
{
if (food <= 0)
{
GameManager.instance.GameOver();
}
}
}
Enemy Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MovingObject {
public int playerDamage;
private Animator animator;
private Transform target;
private bool skipmove;
// Use this for initialization
protected override void Start () {
GameManager.instance.AddEnemyToList(this);
animator = GetComponent<Animator>();
target = GameObject.FindGameObjectWithTag("Player").transform;
base.Start();
}
protected override void AttemptMove<T>(int xDir, int yDir)
{
if (skipmove)
{
skipmove = false;
return;
}
base.AttemptMove<T>(xDir, yDir);
}
public void MoveEnemy()
{
int xDir = 0;
int yDir = 0;
if (Mathf.Abs(target.position.x - transform.position.x) < float.Epsilon)
{
yDir = target.position.y > transform.position.y ? 1 : -1;
}
else
{
xDir = target.position.x > transform.position.x ? 1 : -1;
AttemptMove<Player>(xDir,yDir);
}
}
protected override void OnCantMove<T>(T component)
{
Player hitplayer = component as Player;
animator.SetTrigger("enemyAttack");
hitplayer.LoseFood(playerDamage);
}
}
I'm not sure which whether the player or enemy have an issue of the base script. Can anyone help.
A few Observations (Hopefully it helps):
MovingObject.cs - Inside of Update(), should it not be this?
if (!GameManager.instance.playersTurn)
Note I added a "!" before GameManager
Player.cs - in AttemptMove(), you need to call Move()... like this
Move (xDir, yDir, out hit);
Enemy.cs
1) At the end of AttemptMove(), there should be:
skipMove = true;
2) In MoveEnemy(), at the end, this code should NOT be in the else, but after the else:
AttemptMove<Player>(xDir,yDir);

Categories