Home > OS >  I'm trying to send a boolean from script to script
I'm trying to send a boolean from script to script

Time:11-21

I watched some tutorials on how to send booleans from script so script and this is the code I wrote:

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

public class sender : MonoBehaviour
{
    public bool ktp;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
             bool ktp = true;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
    }
}

and

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

public class empfänger : MonoBehaviour
{
    public sender script;

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        if (script.ktp == true)
        {
            Debug.Log(script.ktp);
        }
    }
}

I'm testing on sending booleans from script to script and here I'm just trying to output the boolean declared from another script to the console.

I was expecting it to work.

CodePudding user response:

You are essentially ‘creating’ the variable twice. In sender, remove the bool from the when you are assigning the variable in the function.

sender.cs

using System.Collections.Generic;
using UnityEngine;

public class sender : MonoBehaviour
{
    public bool ktp;
    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
             ktp = true;
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
  • Related