instantiating an object at a specific position - c#

been trying to do this for the past hour here is the code I have so far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class clone : MonoBehaviour
{
public GameObject fruit;
void Update()
{
Instantiate(fruit);
}
}

There are multiple overloads of Instantiate documented and it even returns the GameObject, so you can manipulate the position.
Either:
Instantiate(fruit, new Vector3(1,2,3), Quaternion.Identity);
or:
GameObject obj = Instantiate(fruit);
obj.transform.position = new Vector3(1,2,3);
Note: Your code spawns objects every frame as it's in Update() - you should do in in a function that is triggered by a KeyPress or do it in Start which is called once in the beginning. You could use a loop if you need multiple fruits.

Related

Unity Transform not updating position realtime

I am trying to create a simple scriptable object for my shoot ability. I have that aspect working, but as I try to set my Transform to my player, it does not update the shoot position. I am very new to C#, and this script isnt complete. I still need to add the functionality to destroy the created objects. Any help would be greatly appreciated. I suspect I need to add an update function but im am not certain how to do this.
using UnityEngine.InputSystem;
using UnityEngine.AI;
using UnityEngine;
namespace EO.ARPGInput
{
[CreateAssetMenu]
public class Shoot : Ability
{
public Transform projectileSpawnPoint;
public GameObject projectilePrefab;
public float bulletSpeed = 10;
public float bulletLife = 3;
public override void Activate(GameObject parent)
{
var projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);
projectile.GetComponent<Rigidbody>().velocity = projectileSpawnPoint.forward * bulletSpeed;
Destroy(projectile, bulletLife);
void OnCollisionEnter(Collision collision)
{
Destroy(projectile);
}
}
}
}
I'm still new to Unity and coding also, so take my advice with a load of salt :P.
It may be best to have a transform on your character (say just past the barrel of the player's gun) that you can put as the projectileSpawnPoint. In your code the projectileSpawnPoint is never set. Your first line of code in the "Activate" method should be something like:
public override void Activate(GameObject parent)
{
projectileSpawnPoint = playerGunBarrelTransform.transform.position;
var projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);
projectile.GetComponent<Rigidbody>().velocity = projectileSpawnPoint.forward * bulletSpeed;
Destroy(projectile, bulletLife);
For destroying the projectile afterward you can keep it as you have it in OnCollision. howeer, with bullets in particular, since they tend to be instantiated A LOT and then destroyed afterward it would be best to use an object pooler for them to instantiate several of them on start and then disable and enable them as needed so you can resuse them instead of making new ones every time.
you have to create a new script that derives from Monobehaviour for your projectiles. attach that script to the projectile prefab and place the OnCollisionEnter method in that script. now your projectiles should get destroyed when touching another collider. make sure that there is a rigidbody component attached to the projectile.

Spawned objects don't show on the surface of the position i wanted them to show

I have a script where i click and spawn objects out of the bushes. the problem is when the Item is spawned which is shown in the heirarchy as (Clone) doesn't show in play mode can't see it anywhere.
this is the picture of the play mode:
and this is the script for the spawning objects i don't know if i'm doing something wrong in randomizing the position:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomObjectSpawner : MonoBehaviour
{
public GameObject[] myObjects;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
int randomIndex = Random.Range(0, myObjects.Length - 1);
Vector3 randomSpawnPosition = new Vector3(Random.Range(-10, 11), 5, Random.Range(-10, 11));
Instantiate(myObjects[randomIndex], randomSpawnPosition, Quaternion.identity);
}
}
}
I'm assuming that the spawned objects are also Canvas Objects. So you have to set the parent to somewhere inside the canvas.
This can be done directly with the instantiate method. You can add the transform of the parent as a fourth parameter for your Instantiate method.
To do that add public Transform groupTransform; in your RandomObjectSpawner class. Change your Instantiate line to:
Instantiate(myObjects[randomIndex], randomSpawnPosition, Quaternion.identity, groupTransform);
Then in the Editor drag your Group Gameobject to the groupTransform field on the RandomObjectSpawner script.

I need help for spawning enemies in unity 2d

I have problem spawning enemies in unity 2d. Enemies clones themselves too quickly and it lags. Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject enemy;
public float spawnTime = 5f;
public float spawnDelay = 3f;
// Use this for initialization
void Start () {
InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
}
void addEnemy() {
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position,
spawnPoints[spawnPointIndex].rotation);
}
}
Oh, I am currently making a 2D game where I have to spawn enemies and here is what code I used, edited for you of course:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
public float interval = 100;
private float counter = 0;
// Update is called once per frame
void FixedUpdate()
{
counter += 1;
if(counter >= interval){
counter = 0;
Instantiate(enemyPrefab, transform.position,transform.rotation);
}
}
}
Simply create a new game object, put this script it, add the enemy prefab in the Game Object variable and you are set. You can edit the interval between each enemy with the interval variable. Good luck with your project :)
I'm assuming they are spawning more than every 3 seconds? Do you have multiple 'EnemySpawner' scripts attached to objects in the scene?
edit sounds like you have an ‘EnemySpawner’ script in your prefab, remove it from prefab and put it on a separate GameObject in your scene.
You should not as in the accepted answer use FixedUpdate for this! It uses 100 fixed update steps .. but who wants to calculate how long this actually takes?
By default fixed update step is 0.02s so 100 means 2 real-time seconds - but what if you change the fixed update step for any reason?
I would rather do it using a simple timer in Update:
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
// In seconds
[SerializeField]private float interval = 2f;
private float timer = 0f;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if(timer >= interval){
timer = 0f;
Instantiate(enemyPrefab, transform.position,transform.rotation);
}
}
}
Actually what you had should also work! Depends of course also on the values you set via the Inspector.
BUT What I can see from the image you posted is: In enemy you referenced the object itself!
=> The next time there are 2 enemy instances including this spawner
=> The next time there are 4 enemy instances including this spawner
=> The next time there are 8 enemy instances ...
=> etc
Therefore they are called Enemy[Clone] then Enemy[Clone][Clone] then Enemy[Clone][Clone][Clone] etc so
Not sure if this was intended but I would rather put the spawner script on one single object in the scene and rather reference a prefab without an additional spawner script.

Can the FireComplex particle be activated on trigger only?

I am using the FireComplex particle to generate an explosion (a bomb) when the user presses spacebar. The fire is playing on awake which I don't want and it doesn't seem to include an option to disable it.
Can this be coded to only activate the fire particle when I press space? I have tried the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatController : MonoBehaviour {
//public GameObject enemy;
[SerializeField]
public GameObject Bomb;
public GameObject Fire;
if(Input.GetKeyUp(KeyCode.Space)) {
BombExplosion ();
}
public void BombExplosion () {
//Create the Bombs Explosion Particle Effect.
Instantiate (Fire, this.gameObject.transform.position, Quaternion.identity);
Fire.Emit(5); //Burn for 5 seconds
}
Unity seems to be ignoring the Fire.Emit function.
The reason, I think, why the Bomb goes off after executing the game is because of the onviously incorrect logic in GetKeyUp. I doubt that it what you need.
Change it to GetKey instead.
Hope that clarifies the issue.

Unity3d not liking collision

using UnityEngine;
using System.Collections;
public class chicken_for : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (collision.gameObject.Quad == collisionObject){
Application.LoadLevel("SciFi Level");
}
}
}
I am attempting to when A person touches a quad, he goes to this sci-fi fortress. It however says the name 'collision' does not exist in the current context.
You're referencing a variable (collision) that doesn't exist. You've got a variable collisionObject that doesn't exist, too.
collision is typically the name of the argument to the OnCollisionEnter method. Your code should probably be inside this method instead of FixedUpdate. I'm guessing that you've copied code from a tutorial somewhere but put it in the wrong method.
collisionObject on the other hand is harder to guess, but I expect that if your script is intended to be a component on the player object, then collisionObject should be your quad; if the script is on the quad then collisionObject should be the player.
Either way, you need to declare that variable - probably as a public field so that you can populate it from the inspector.
Add a new function and make sure the player is tagged as player in the inspector. You also need to make sure that there is a collider on the quad that the player touches and a rigidbody component on the player.
using UnityEngine;
using System.Collections;
public class chicken_for : MonoBehaviour {
//This function will handle the collision on your object
void OnCollisionEnter (Collider col){
if(col.gameobject.tag == "Player"){ //if colliding object if tagged player
Application.LoadLevel("SciFi Level"); //load the sci-fi level
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
This should get you roughly where you want to be!

Categories