Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Destroying a prefab after clicking on it.

Discussion in 'Prefabs' started by ryandobal_unity, Apr 14, 2020.

  1. ryandobal_unity

    ryandobal_unity

    Joined:
    Mar 16, 2020
    Posts:
    6
    Hello,

    I am working on a game where instantiated cubes from prefabs are floating around. What I am trying to do is when I click on the instantiated prefab, it destroy's itself and increases my "score" integer in my GameManager by one.

    I have two issues which I can't figure out. Here are the two issues:
    1. I am having trouble changing the score in GameManager from the prefab itself. I cannot drag and drop my Game Manager into my Game Manager area I made in the script on the prefab. I thought it would be fairly easy, simple by doing:

    Code (CSharp):
    1. public GameManagerScript gameman;
    2.  
    3. public void isClicked() {
    4.       gameman.score++;
    5. }
    6.  
    however it does not work.

    (I did not do the code in the exact context as there are many things in between which are not relevant to this thread)

    2. Destroying the prefab after the click. I got the click part working and it prints "A prefab was clicked!" in console, but I can't actually get it to destroy.

    If anyone can help it would be much appreciated. Also, if anyone thinks they can help but needs more information about the issues, please let me know! I am new to prefabs and honestly don't know what to do haha!

    Thank you in advance!
    Ryan
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi,

    @ryandobal_unity check into static variables and Singletons. They will come handy sometime in near future when you develop your game.

    To get easy access to your score field or property, you could just make it static in your GameManager:

    Code (CSharp):
    1. public static int score;
    Now, you can access it from your block object and from elsewhere like this:
    Code (CSharp):
    1. Manager.score++;
    Another alternative that would be less coupled would be to use events.

    If your click detection is working, good, but to destroy it you would just do something like this:
    Code (CSharp):
    1. Destroy(this.gameObject);
    This will destroy the GameObject instance your script containing that code is attached to. If you would just use Destroy(this), you would destroy the script instance, but not the GameObject.

    These are all quite easily to be found, so I'd recommend working also on your google-fu, as you need to do a lot of searches all the time when coding.