Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by radar089 · Nov 23, 2015 at 03:52 AM · activatespawner

Activate a script if an object is in the game world?

So i have an enemy spawning script, and i only want it to activate if another object is in the game world/when i place the object in the world. i have no clue how to express that i am so new to scripting. can someone help me add that line of code to the script please?

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 #if UNITY_EDITOR
 using UnityEditor;
 #endif
 public class EnemySpawner : MonoBehaviour
 {
 
     public GameObject[] Objectman;
     public float TimeSpawn = 3;
     public int MaxObject = 10;
     public string PlayerTag = "Player";
     public bool PlayerEnter = true;
     private float timetemp = 0;
     private int indexSpawn;
     private List<GameObject> spawnList = new List<GameObject> ();
     public bool OnActive;
     
     void Start ()
     {
         indexSpawn = Random.Range (0, Objectman.Length);
         timetemp = Time.time;
     }
 
     void Update ()
     {
         OnActive = false;
         if (PlayerEnter) {
             // check if player is enter this area
             GameObject[] playersaround = GameObject.FindGameObjectsWithTag (PlayerTag);
             for (int p=0; p<playersaround.Length; p++) {
                 if (Vector3.Distance (this.transform.position, playersaround [p].transform.position) < this.transform.localScale.x) {
                     OnActive = true;
                 }
             }
         } else {
             OnActive = true;
         }
         
         bool offlineMode = (!Network.isServer && !Network.isClient);
 
         if (!OnActive)
             return;
         
         ObjectExistCheck ();
         if (Objectman [indexSpawn] == null)
             return;
         
         // spawn if ObjectsNumber is less than Max object.
         if (ObjectsNumber < MaxObject && Time.time > timetemp + TimeSpawn) {
             timetemp = Time.time;
             GameObject obj = null;
             Vector3 spawnPoint = DetectGround (transform.position + new Vector3 (Random.Range (-(int)(this.transform.localScale.x / 2.0f), (int)(this.transform.localScale.x / 2.0f)),0, Random.Range ((int)(-this.transform.localScale.z / 2.0f), (int)(this.transform.localScale.z / 2.0f))));
             if (!offlineMode) {
                 if (Network.isServer){
                     obj = (GameObject)Network.Instantiate (Objectman [indexSpawn], spawnPoint, Quaternion.identity, 0);
                 }
             } else {
                 obj = (GameObject)GameObject.Instantiate (Objectman [indexSpawn], spawnPoint, Quaternion.identity);
             }
             if (obj)
                 spawnList.Add (obj);
             indexSpawn = Random.Range (0, Objectman.Length);
             
         }
     }
     
     private int ObjectsNumber;
 
     void ObjectExistCheck ()
     {
         // checking a number of all objects. that's was spawn with this spawner
         ObjectsNumber = 0;
         foreach (var obj in spawnList) {
             if (obj != null)
                 ObjectsNumber++;
         }
     }
     
     void OnDrawGizmos ()
     {
         #if UNITY_EDITOR
         Gizmos.color = Color.red;
         Gizmos.DrawSphere (transform.position, 2);
         Gizmos.DrawWireCube (transform.position, this.transform.localScale);
         Handles.Label(transform.position, "Enemy Spawner");
         #endif
     }
     
     Vector3 DetectGround (Vector3 position)
     {
         RaycastHit hit;
         if (Physics.Raycast (position, -Vector3.up, out hit, 1000.0f)) {
             return hit.point;
         }
         return position;
     }
     
 }
 

Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jmgek · Nov 23, 2015 at 06:06 AM 0
Share

No one is going to read through 100 lines of code to guess what you want to do. If you want to check if a game object is in a scene you can use

Gameobject.find("scriptname");

avatar image radar089 jmgek · Nov 23, 2015 at 09:50 PM 0
Share

what is the ("scriptname") part for?

so i can use gameobject.find to find an object, but then how do i make the script itself activate?

avatar image jmgek radar089 · Nov 23, 2015 at 10:00 PM 0
Share

I don't understand what you want to activate? The class?

 GameObject cubeScript = GameObject.find("CubeScript");
 cubeScript.GetComponent<ScriptOnCube>();
 
Show more comments

4 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by MobinYaqoob · Nov 23, 2015 at 09:18 AM

On Line 60 : obj = (GameObject)GameObject.Instantiate (Objectman [indexSpawn], spawnPoint, Quaternion.identity); just add a line :

  obj.AddComponent<WhatScriptYouWantToAttach>();

it will add the script as it instantiate to what ever place Happy Codding :)

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by sandeepsmartest · Nov 23, 2015 at 06:38 AM

To check if object is in active state use this

 if(Player.activeInHierarchy)

then activate the game object for which the enemy spawning script is attached by simple using this

 EnemySpawningObj.SetActive(true);

Hope this may help you. Nsks

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by radar089 · Nov 23, 2015 at 09:44 PM

sorry everyone, this is kinda hard for me to explain. the script i posted above, i only want it to be activated when another object is in the scene. a cube, anything, so i would have to have a public variable for that object right? so the script knows what object to look for?

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jmgek · Nov 23, 2015 at 09:54 PM 0
Share

If are checking a scene for a object I would suggest using the GameObject.Find("Cube"); http://docs.unity3d.com/ScriptReference/GameObject.Find.html

 if(GameObject.Find("Cube"))
     Debug.Log("There is the Cube in the scene");

This will check the scene for the object.

OR you can put a public var like you suggest in a game manager, but I would not suggest it:

 CubeScript.cs
 private void Start()
 {
     Game$$anonymous$$anager gm = new Game$$anonymous$$anager();
     gm.cubeIsInTheScene = true; 
 }

 Game$$anonymous$$anager.cs
 {
      public bool cubeIsInTheScene = false;
 }
avatar image radar089 jmgek · Nov 23, 2015 at 09:58 PM 0
Share

ok cool i understand that part, thank you for that help. but now how would i tell this script to only activate if the object is present in the scene?

avatar image
0

Answer by jmgek · Nov 23, 2015 at 10:29 PM

the entire script i posted above. after i add "if(GameObject.Find("Cube"))" then i want to activate the script itself. i only want the script to run if it find the predetermined object.

I'm really sorry I cant understand what you're saying.

If you want to see if an object is in the scene use

 GameObject cube = Gameobject.Find("NameOfTheCube");


Once you have found that game object get the component 'Script' from it with:

 CubeScriptYouWantToActivate cs = cube.GetComponent<CubeScriptYouWantToActivate>();
 
 CubeScriptYouWantToActivate.SetActive(true);
 CubeScriptYouWantToActivate.CallAnyMethod();
 CubeScriptYouWantToActivate.CallAnotherMethod(true);
 CubeScriptYouWantToActivate.SetFloatInsideScript(11);

Then this is the script on the object:

 CubeScriptYouWantToActivate.cs

 public void CallAnyMethod()
 {
     this.GameObject.SetActive(true);
 }
 public void SetFloatInsideScript(float number)
 {
     Debug.Log(number);
 }

"i would need to check for the gameobject before or in the void start/void update parts right? and if gameobject.find is true then the rest will start right?"

Correct, you should have a manager in the scene that checks to see when things are edited or not. It's not good practice to have one script rely on another without having a manager because 1. you cant debug it well 2. if you come back later or someone else works on the project they have no idea what or how things are being activated.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image radar089 · Nov 23, 2015 at 10:41 PM 0
Share

ok, the spawning script above spawns my ai. i only want the script to run if an object of my choosing is present in the scene. forgive me i dont know how to express this in csharp but what i want the script to do is check and see if the object is in the scene, before the rest of the script starts running.

avatar image jmgek radar089 · Nov 23, 2015 at 10:47 PM 0
Share

$$anonymous$$ake a cube in the scene and make a test script and name it Test.cs and attach the Test.cs script to the cube: Now put this inside the Test.cs:

 //Test.cs
 
 Public void Call$$anonymous$$ethod()
 {
      Debug.Log("You have called a method on " + this.gameObject.name);
 }

Now make a empty game object and name it Game$$anonymous$$anager and make a script and name it Game$$anonymous$$anager.cs attach the Game$$anonymous$$anager.cs to the Game$$anonymous$$anager object in the scene and and put this in it:

 //Game$$anonymous$$anager.cs
 private void Start()
 {
      GameObject cube = Gameobject.Find("cube");
      if(cube)
      {
           Test test = cube.GetComponent<Test>();
           test.Call$$anonymous$$ethod();
      }
      else
            Debug.Log("There is no cube in the scene");
 }



Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

34 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Problem activating 1 Answer

Activate a Object 1 Answer

Trigger activation? 1 Answer

Script not working anymore 1 Answer

Can't Activate a GameObject Because of a Clon Enemy 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges