Search Unity

Mke it so when an object collides with an object in a scene it destroys the object in the menu scene

Discussion in 'Scripting' started by DavidTurn, Aug 5, 2019.

  1. DavidTurn

    DavidTurn

    Joined:
    Jul 29, 2019
    Posts:
    5
    I have No Idea Whats going on. This is My first time using a coding language to make a game. HTML and Scratch.com are not real coding things. I dont know anything about the syntax of Csharp dont explain me anything
    just give me the code for my problem and nothing else. The object Nothing is in the menu scene i want something to happen to it. This code is on the thing the player has to collide with to destroy the thing in the menu. i tried moving it wile it is dont destry ol loadd but that cant happen so i cant use dont destroy on load because dont destory on load was on Nothing the game object. im litterally so confused rn
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class SubwayKey : MonoBehaviour
    7. {
    8.     private void OnTriggerEnter(Collider other)
    9.     {
    10.         if (other.gameObject.tag != "Player")
    11.         {
    12.             void SetTransformX(float n)
    13.             {
    14.                 GameObject.Find("Nothing").transform.position = new Vector3(n, transform.position.y, transform.position.z);
    15.             }
    16.             void Update()
    17.             {
    18.                 SetTransformX(7.0f);
    19.             }
    20.         }
    21.     }
    22. }
    23.  
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You've got function definitions inside function definitions, is the main thing here. Take lines 12-19, and move them outside of the OnTriggerEnter function (outside of the { }). Generally, all your function definitions need to be directly inside the "public class X : MonoBehaviour {" block.

    Once you do that, it should run, but you'll find that it's setting the "Nothing" object's position every frame, which seems to be not what you want. That's because Update() runs every frame. What you actually want is to call SetTransformX(7.0f); in the if statement, which I assume is what you were trying to do and how those functions ended up inside there. But really, you just want line 18 inside there, and nothing inside Update(). (You can delete Update() entirely if you want)