Connecting two scripts to SetActive false and SetActive true two separate objects with their own scripts

Hi all you lovely developers! I have two scripts attached to seperate objects, and im having a wild time wrapping my mind around accessing methods and variables from another script. I simply would like to when I press E set active an object (sword) that is infront of the player always. and when left alt and left click are pressed itll setactive false that sword again and setactive true the thrown sowrd which is initially disabled. but when enabled has a constant moving forward and spin to it. I cannot get it to work and I assume its because I cant get my mind around calling methods from another script. Any help is greatly appreciate folks! Have a lovely day!

SCRIPT 1:

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

public class swordHandler : MonoBehaviour
{
    public bool canThrow = false;  // Player can toss le sword

    public TMP_Text pressE;
    public GameObject playerSword;  
    public GameObject ricochetObject;  

    void Start()
    {
        pressE.enabled = false;  // Start with the "Press E" message hidden
        playerSword.SetActive(false);  // Player sword is initially inactive
        ricochetObject.SetActive(false);  // Ricochet script is initially inactive
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("canPickup"))
        {
            Debug.Log("Player can pick up the sword");
            pressE.enabled = true;  // Show "Press E" when near the sword
        }
    }

    private void OnTriggerStay(Collider other)
    {
        if (Input.GetKeyDown(KeyCode.E) && other.CompareTag("canPickup"))
        {
            Debug.Log("Item picked up!");

            // Deactivate the pickup object (set it to inactive)
            other.gameObject.SetActive(false);
            pressE.enabled = false;

            // Activate the player's sword
            playerSword.SetActive(true);
            Debug.Log("Player sword is active");

            // Set canThrow to true, meaning the player can now throw the sword
            canThrow = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("canPickup"))
        {
            Debug.Log("Nothing to pick up");
            pressE.enabled = false;  // Hide the "Press E" message when leaving the area
        }
    }
}

Script 2:

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

public class Ricochet : MonoBehaviour
{
    public swordHandler swordHandlerScript;  // Reference to the swordHandler script (which I don't understand or think this is right)

    private Rigidbody rb_thrownSword;
    public float thrust = 200f;
    public float throwSpinSpeed = 100f;

    public GameObject thrownSword;  // the spinning boi

    private bool isThrowing = false;

    void Start()
    {
        rb_thrownSword = thrownSword.GetComponent<Rigidbody>();  // Get le rgid boy
        rb_thrownSword.isKinematic = true;  // dont let it go yet. or me im very alone
        thrownSword.SetActive(false);  // jack...Dont let go. 
    }

    void Update()
    {
        // check if all conditions are met. kinda like dating in 2024
        if (swordHandlerScript != null && swordHandlerScript.canThrow)
        {
            if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButtonDown(0))
            {
                // I think if f*cked something here up
                if (!isThrowing)
                {
                    isThrowing = true;

                    // no sword (This is really bad program noting.
                    swordHandlerScript.playerSword.SetActive(false);
                    Debug.Log("Player sword deactivated");

                    // Activate the thrown sword
                    thrownSword.SetActive(true);
                    SwordThrow();
                }
            }
        }
    }

    private void SwordThrow()
    {
        Debug.Log("Throwing the sword!");

        rb_thrownSword.isKinematic = false;  
        rb_thrownSword.AddForce(transform.forward * thrust, ForceMode.Impulse);  // sword go wee

        // you spin me right round baby right round
        rb_thrownSword.AddTorque(transform.right * throwSpinSpeed, ForceMode.Impulse);

        isThrowing = false;  // Reset the throwing
    }
}

Hi!

I haven’t used OnTriggerEnter() before; is it constantly running? Or is it only checking once and not again? But otherwise the code seems to make sense. At what point is it not working?
e.g. Are you able ot get the “Press E” show up?
Are you able to pick up the sword (set Active)?

Cheers

Hey! Thanks for the reply and interest! It all functions nominally until after the first sword is SetActive True upon entering and staying on collision trigger. Outside of that im aiming to when I press E 'the script attached to the item that shows up when you press E on collision. to SetActive the thrown sword which has a constant addforce and disable parent mechanic, however I cant seem to get the scriots to communicate properly with eachother as the thrown blade has its own script that only gets or at leat im trying to get the first script to set that object to active and set itself to innactive just after. I’ve tried seeing if its a logiv thing but in doing so ive entirely broken it haha. Hope that helps at all! I only want you to be able to set thte thrown one as active once youve picked up the sword so theres a picked up variable that is canThrow which does check as ive set it to public so i can see that its checked in the inspector. I just cant get the sword thats first revealed to disable and well firstly enable the thrown object then disable itself

Hi again Liam!

Im afraid I hadnt properly communicated what I was trying to say as I’m terrible at communication but heres a youtube link for my game runtime. As you can see upon compiling (which for some reason took forever this time) Theres two swords in view, both are inactive via script upon compilation. When the player enteres the comparetags for collisionEnter and CollisionStay under the conditions that alt left and left click are met it performs nominally until i got to throw it and it just simply doesnt communicate the set active switch. Cheers hope this clears it up!

Since I cannot debug what you have above, my first suggestion is to make sure you have familiarized yourself with one of the thousands of “PRESS E TO DO ACTION” tutorials out there.

Because code / objects get turned on / off (activated, deactivated), reasoning about what code should stay running and which object it needs to be on can be a little tricky.

Beyond that, honestly it just sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Honestly would not shock me if I have. Really been pushing to learn code so I cna get good enough to identify these issues like a whizz one day. Might try re writing it using a different method tbh. Perhaps I can handle all the set active and unsetting on the one handler and just give the thrown sword the moving machanics and negate the communication issues entirely.

A huge part of it is just diligence with tracking down what is going on, using the tools listed above.

Remember: Code does not (really) matter. The data matters. The data reveals what the code is doing to it.

Because our simple primate brains can only handle so many things at once, often it is helpful to greatly simplify your problem space, such as making an “PRESS E” sensor that does nothing more than show / hide that message until you have that working 100%, the moving on to make E actually do something at the appropriate time.

I do this process all the time: in fact I do it before I have issues: I build tiny little baby steps, testing each step of the way. The instant something misbehaves I stop until I sort it all out.

And you don’t have to follow tutorials, but they sure can give you a leg up on thinking of the problem space because odds are you will be having to solve all the same issues they did.

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

1 Like

Yea, thats sort of how ive been approaching it, i take bits and bops from tutorials, play with it a little to see what breaks, start writing my own methods and see if that works, sometimes it does sometimes it doesn’t when it doesn’t I get a better opportunity to understand why and its really been helping. Debugging though you’re right has definitely been a god sent.

Excellent news kurt, so Ive moved the whole function into update (yes somehow I hadnt thought to do that) and its starting to work however is really hit or miss and takes multiple attempts. Am I using the wrong get key method? Does it have to be pushed at the EXACT same time the way iim doing it? Or is there a faster method than update to put it in? Cheers!

Ok one last post its been awesome progress over here. Ive got it working essentially how I want it except for that fact that when unparented the sword and (im doing this in baby steps) right now i just want it to drop infront of the player currently it just goes to a deault world position and since it doesnt use gravity just sorta sits there, I beleive where it spawns initially how can I change it so its dropped at its current world position?