How to instantiate nonpublic prefab - c#

I instantiate prefabs by dragging them into a variable in the scene. Here's the code:
public GameObject player1;
void Start()
{
Instantiate(player1, spawn.position, spawn.rotation)
}
I don't want to drag and drop. How do I accomplish this?

Put your prefab in the Assets/Resources folder.
Then you can find the prefab and then instantiate it.
private GameObject player1;
void Start()
{
player1 = Instantiate(Resources.Load("Player1"), spawn.position, spawn.rotation) as GameObject;
}
"Player1" is the name of the prefab. You can call it what you want.
You can do this with any prefab or other data, such as textures. More information on Resources.Load on Unity API.

Related

How can i clone an object one by one in unity

So basically i wanted to learn about instantiate and I have tried this code below:
public Transform spawnpos;// the position where i wanted to clone my sphere
void Update()
{
if (Input.GetKeyDown("q"))
{
Instantiate(gameObject, spawnpos.position, spawnpos.rotation);
Destroy(gameObject, 2);
}
}
the thing is, when i press "q" it does spawn a sphere and gone in about 2 secs, but if i continously press "q" the amount of clones spawned are getting bigger as i press and it wont be destroyed after 2 seconds.
In Conclusion, how can i spawn a sphere when i pressed "q", and it will spawn 10 if i pressed "q" 10 times
tysm for reading this far! have a nice day! :)
First thing's first, you can't instantiate the gameobject to which this script is attached through this script because:
If you instantiate a gameobject, there will be two gameobjects in the scene and both will be having this script. Hence if you press Q again, two gameobjects are instantiated.
Solution:
Create an empty gameobject in the scene and create a new script ObjectSpawner.cs and attach it to this empty gameobject.
public class ObjectSpawner : MonoBehaviour {
public Transform spawnpos;// the position where I wanted to clone my sphere
public GameObject sphere;// gameobject you want to spawn
void Update() {
if (Input.GetKeyDown("q")) {
GameObject obj = Instantiate(sphere, spawnpos.position, spawnpos.rotation);
Destroy(obj, 2);
}
}
}
In the above script as you can see there's a field for the sphere gameobject. Drag it to the slot in the inspector.

Unity - Affect only clicked GameObject

I am new to unity, and I tried to create a prefab for a tile in a game. So whenever a user clicks the tile it should change its sprite. The problem is that all the copies (instances) in my game are changing their sprite.
This is what I tried:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject gameObject = this.gameObject;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
}
What am I doing wrong? Thanks in advance
You are detecting if the mouse button is pressed, not if it's pressed over the given tile.
There are several ways to do it, but I would say the standard way is to:
Attach a Collider to the GameObject
Implement OnMouseDown
void OnMouseDown()
{
GameObject gameObject = this.gameObject;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
Like akin said you are changing all sprites on a mouse click, you can raycast to your objects and check if they are hit then change it
Run this part on a script attached to your player or camera
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0f)) {
if (hit.transform.gameObject.GetComponent<yourscript>()) {
hit.transform.gameObject.GetComponent<yourscript>().ChangeSprite();
}
}
}
attach to tile game objects
public class yourscript : MonoBehaviour
{
public void ChangeSprite() {
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Sprites/red");
renderer.sprite = sprite;
}
}

OntriggerEnter not called playerController

I have a script that is a attached to a box, the box has two colliders on for physics and one (slightly bigger) for detecting OntriggerEnters when my player walks over it. I have a script attached to the box that does the following:
public class ColorChangeCollision : MonoBehaviour {
private GameObject Element;
private Color32 BaseColor, CollisionColor;
private Material ElementMaterial;
void Start () {
Element = this.gameObject;
BaseColor = new Color32(255,255,255,255);
CollisionColor = new Color32((byte)Random.Range(0, 255),(byte)Random.Range(0, 255),(byte)Random.Range(0, 255), 255);
ElementMaterial = Element.gameObject.GetComponent<Renderer>().material;
}
private void OnControllerColliderHit(ControllerColliderHit other)
{
Debug.Log("collision...");
ElementMaterial.color = CollisionColor;
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("enter");
}
private void OnTriggerStay(Collider other)
{
Debug.Log("staying..");
}
private void OnTriggerExit(Collider other)
{
Debug.Log("left...");
ElementMaterial.color = BaseColor;
}
}
Main problem OnTriggerEnter or OnControllerColliderHit is never called nor are the other trigger events..
See below for an image of the setup of the box, and its components:
See here for my player who should be calling the OntriggerEnter or OnControllerColliderHit function of the box:
EDIT I modified all the elements to the suggestions of #Programmer. But the OnControllerColliderHit event is still not being called.. (note this function is attachted on the box )
There are 3 issues on how you setup your scene and your code:
1. You are missing a Rigidbody. This should be attached to the "Cube" GameObject since it's not ok to attach Rigidbody to GameObject with a CharacterController.
2. You have two BoxColliders attached to one GameObject ("Cube"). Do not do this. This can cause many issues including a callback function being called multiple times or non at-all.
What to do when you need both trigger and non trigger collider?
Create an empty child GameObject put the trigger there. You can do that.
3. You are using CharacterController so you should remove the OnTriggerXXX callback functions. When using CharacterController, it recommended to use it's callback function OnControllerColliderHit.
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
......
}
4. CharacterController is not mean to be used as triggers. They are used to detect collisions.
You have two options to make it detect triggers:
A. Remove the isTrigger from the "Cube" Object
Or
B. Add a child empty GameObject under the CharacterController then add the CapsuleCollider or any other collider to it. You don't have to mark it as isTrigger since the "Cube" is already marked as so. You also shouldn't have Rigidbody attached to this child collider.
Create a new layer named "CC" and make the CharacterController and the new child GameObject to be in the "CC" layer. Go to your physics collision matrix settings and make it so that "CC" layer cannot collide with "CC" layer. This will make sure that the CharacterController doesn't detect collsion from tis child object.
You can now use your OnTriggerXXX callback functions to detect collision between the CharacterController and the "Cube" object.
One of them needs to have rigidbody to detect collisions.

Play/Stop animation/animator on instantiated object

I'm developing a unity game and basically, I have a prefab with a sprite inside it. I created an animation attached to that sprite.
FrogPrefab
|__ FrogSprite
I created a script with a public field "prefab" where I pass my prefab.
My question is, how can I stop and play this animation from my script.
I instantiated my prefab from my start method...
public GameObject gameCharacterPrefab;
private GameObject frog;
void start() {
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
}
I'm trying to do something like that...
frog.animation.stop();
appreciate any help
First, note that the function should be called Start not start. Maybe this is a typo in the question but it's worth mentioning.
Use GetComponent to get the Animator or Animation component. If the animation is a child of the prefab then use GetComponentInChildren.
If using the Animator component:
public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animator anim;
Instantiate the prefab
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
Get the Animator component
anim = frog.GetComponent<Animator>();
Play animation state
anim.Play("AnimStateName");
Stop animation
anim.StopPlayback();
If using the Animation component:
public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animation anim;
Instantiate the prefab
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
Get the Animation component
anim = frog.GetComponent<Animation>();
Play animation name
anim.Play("AnimName");
Stop animation
anim.Stop();
For playing animation we can use Play() but for stopping the animation the Stop method is become obsolete in Unity 2019 or higher versions. So, For disable animation we can use enable flag and set it to false.
//For playing the animation
frog.GetComponent<Animator>().Play();
or
frog.GetComponent<Animator>().enable = true;
//For stop the animation
frog.GetComponent<Animator>().enabled = false;

Unity: Initializing smoke Prefab via script

I am trying to use a smoke prefab (free asset from Unity asset store). When I add the prefab directly into the game scene, the prefab works:
But when I create the following script to initialize the same prefab (inside a game object), nothing happens:
class Smoke1 : MonoBehaviour
{
public GameObject myPrefab;
void Start()
{
Instantiate(myPrefab, transform.position, transform.rotation);
}
void Update()
{
}
}
My game scene:
Can you help?
Try to use Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);. This will spawn the prefab in the center of the scene. If it works, then it means you're doing something weird with the position and rotation of the object upon instantiation.

Categories

Resources