Unity - Как я могу заставить функцию срабатывать только тогда, когда игрок нажал на нее 3 раза? - PullRequest
0 голосов
/ 27 мая 2019

У меня есть кнопка подсказки в моей игре, но она срабатывает при каждом нажатии на нее. Мне нужно чтобы он срабатывал только один раз каждые 3 клика

Я пытался добавить loadCount = 0 и оператор if

if (loadCount % 3 == 0) { }

но, похоже, не работает

изображение для справки: https://ibb.co/L9LnNDw

Вот сценарий:

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

[ExecuteInEditMode]
public class HintScript : MonoBehaviour 
{

    LineRenderer line;

    // Use this for initialization
    void Start () 
    {

    }

    // Update is called once per frame
    void Update () 
    { 
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint() 
    { 
        FindObjectOfType<AdMobManager>().Hint = true; 
        FindObjectOfType<AdMobManager>().showInterstitial(); 
    }
}

Ответы [ 3 ]

1 голос
/ 27 мая 2019

Вы должны использовать простой счетчик.

Я также изменил и прокомментировал другие "проблемы" в вашем коде:

public class HintScript : MonoBehaviour 
{
    // by adding SerializeField you can already set those references
    // directly in the Unity Editor. This is better than getting them at runtime.
    [SerializeField] private LineRenderer line;
    [SerializeField] private AdMobManager adMobManager;
    // you can still change the required clicks in the inspector
    // Note: afterwards changing it here will have no effect!
    [SerializeField] private int requiredClicks = 3;    

    // counter for your clicks
    private int counter;

    // Use this for initialization
    void Start () 
    {
        // you should do this only once
        line = GetComponent<LineRenderer>();

        // you should also this only do once
        adMobManager = FindObjectOfType<AdMobManager>();

        // If instead you would drag those references directly into the now
        // serialized fields you wouldn't have to get them on runtime at all.
    }

    // Update is called once per frame
    void Update () 
    { 
        line.positionCount = transform.childCount;
        var positions = new Vector3[transform.childCount];
        for (var i = 0; i < transform.childCount; i++)
        {
            position[i] = transform.GetChild(i).position;
        }

        // it is more efficient to call this only once
        // see https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
        line.SetPositions(positions);
    }

    // This is called from onClick of the Button
    public void Hint() 
    { 
        counter++;

        if(counter < requiredClicks) return;

        // Or using your solution should actually also work
        if(counter % requiredClicks != 0) return;

        adMobManager.Hint = true; 
        adMobManager.showInterstitial(); 

        // reset the counter
        counter = 0;
    }
}
0 голосов
/ 27 мая 2019

1. Сохраните статическую / глобальную переменную.

2.Вы не можете остановить уведомления о событиях, поэтому, пожалуйста, добавьте условие (, если условие ) в кодблок внутри кода обработчика события .

0 голосов
/ 27 мая 2019

Вы можете иметь счетчик, чтобы отслеживать, сколько раз игрок нажал.Затем стреляйте, когда этот счетчик на 3.

int amountOfClicks = 0;
void clickme(){
   amountOfClicks++;
   if(amountOfClicks == 3){
      amountOfClicks = 0; 
      YourFunction();     
   }
}

void YourFunction(){
   // do something...

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...