Home > Software engineering >  C# Unity while key pressed if condition true or false
C# Unity while key pressed if condition true or false

Time:10-21

So I'm new to C# I somewhat know Python I couldn't understand how functions work I tried doing something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class collisiondetectorleft : MonoBehaviour
{
    public class Triggerdetecting()
    {
        public void OnTriggerStay(Collider other)
        {
            if (other.attachedRigidbody)
                other.attachedRigidbody.AddForce((Vector3.up * 10);
        }
    }

    void FixedUpdate()
    {
        if (Input.GetKeyDown("space"))
        {
            //I'm so lost
            Triggerdetecting objTriggerdetecting = new Triggerdetecting();
        }
    }

}

I'm trying to create some sort of hitbox by detecting trigger if a button pressed and meets the condition make the object more faster. I tried few ways to call function non of them worked. Thank you for your time. If you unable to understand what I meant you can ask me I'll try to explain in other ways.

Want something like this:

def detection():
    if OnTriggerStay == True:
        moveobject up

if Input.GetKeyDown("space")) == True:
    detection()

CodePudding user response:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class collisiondetectorleft : MonoBehaviour
{
    public class Triggerdetecting
    {
        public void OnTriggerStay(Collider other)
        {
            if (other.attachedRigidbody)
            {
                other.attachedRigidbody.AddForce(Vector3.up * 10);
            }
        }
    }

    void FixedUpdate()
    {
        if (Input.GetKeyDown("space"))
        {
            Triggerdetecting objTriggerdetecting = new Triggerdetecting();
            objTriggerdetecting.OnTriggerStay();
        }
    }
}

CodePudding user response:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class collisiondetectorleft : MonoBehaviour
{
    //create bool to set it true or false while inside the object
    private bool _canHit;

    private void Update()
    {
        if (_canHit)
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                _canHit = false;
                //task
            }
        }  
    }
    //set _canHit true if object enters trigger
    private void OnTriggerEnter(Collider other)
    {
        if (other.attachedRigidbody)
            _canHit = true;
    }
    //set _canHit false if object exits trigger
    private void OnTriggerExit(Collider other)
    {
        if (other.attachedRigidbody)
            _canHit = false;
    }
}

I was able to detect and log while true but I didn't figured how to react to object that triggers

  • Related