i'm trying to instantiate several prefabs in front of the camera using this code:
public GameObject prefab;
private uint instantiatedPrefabs = 0;
public void createObj()
{
if(instantiatedPrefabs < 10)
{
Instantiate(prefab, new Vector3(1, prefab.GetComponent<Renderer>().bounds.size.y/2, 1), Quaternion.identity);
instantiatedPrefabs++;
}
}
It works flawlessly, but if a new prefab appears inside one or several preexisting prefabs, then the preexisting prefabs experience something like an explosion and get flown away of the new one.
How can i detect there are prefabs in the position where i want to put the new prefab and gently move them to the sideways to open enough space?
Easiest would be to have a patter in mind like a grid or something. So you know you're going to spawn 10 game objects so just place them at like new Vector3(1 , instantiatedPrefabs , 1) so they'll just be in a vertical line. You can have a variable for x position.
Related
I am working on a management game where every user has some specific characters in save files. I am instantiating these characters inside a panel, I want the user to choose one of the cards and drag it to some specific point. I am able to make a drag script for the object that is already in a scene. But how to achieve the same thing if objects are generating at runtime?
I just need some idea how to do it.
here's my current code to drag UI object.
public void OnDrag(){
btn.transform.position = Input.mousePosition;
}
public void EndDrag(){
if (btn.transform.position.x -500 <50 || btn.transform.position.x -500 > -50) {
//btn.transform.position = new Vector3 (-10, 10);
rt.anchoredPosition = new Vector3 (500, 100, 0);
}
else{
rt.anchoredPosition = new Vector3 (-10, -10, 0);
}
}
At the time you Instantiate your GameObject obj, do:
obj.addComponent("YourScript");
where YourScript is your script, which you have written, that attached to a GameObjects makes it draggable..
Alternatively, you instantiate a prefab, attach the script to the prefab through the editor.
This is preferrable because addComponent() will get deprecated in the next versions.
I also recommend to keep a List<YourInstantiatedObjectType> in the parent.
I'm trying to learn Unity by myself. I'm recreating pong in 3d with Unity objects. I started a few minutes ago and every time I throw any input into the pad its y coordinate shifts to 2.6, I have no idea why. Can someone help?
public class PadMovement : MonoBehaviour {
private CharacterController pad;
private Vector3 direction;
private Vector3 movement;
[SerializeField] private float speed = 50.0f;
// Use this for initialization
void Start() {
pad = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update() {
direction = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
movement = direction * speed;
pad.Move(movement * Time.deltaTime);
}
}
SOLVED: there was a capsule collider out of place!
Afternoon, I recently copied your code into a 'Unity3d', ".cs", File and actually I created a cube and placed my game into a 2d mode, After this I named my file "PadMovement", after that I dragged it onto my newly created cube, Once I had done that I tried to click play and noticed that my cube didn't have a "CharacterController", attached to my cube, Once I had done that and clicked play I was eligible to have my "paddle", smoothly move around the screen # 50.0f along the X axis.
Knowingly, My Input came from the "Character Controller", My Speed came from the Serial field you had for speed!
Do you by any chance have a CapsuleCollider Component or some other collider on the same GameObject that you have this PadMovement Component on? That sounds like a height where it might just be trying to pop the object out of ground collision.
It should be harmless if that's all it is. If you really want an object to be at y of 0 you can attach it to a parent object and have that parent stay at 0.
I have made a gameobject together with some children gameobject to represent the information to show up when specific circumstances occurred.
I have already ajusted the position of the information gameobject(together with its' children) in the cameraarea. The thing is that I want to move the gameobject(together with its' children) out of the camera, maybe on top or maybe on left. Following is the scratch to demonstrate the position I want to put it:
So that I could move the information gameobject and its' children (Red box) with some movement effect when needed, I have no problem with moving it back but could find an elegant way to move it out of the camera when the game started.
Mostly because I don't know how to calculate the position out of the camera.
Maybe find the upper border of the camera and the size of the gameobject and its children?
I know I could do this by maybe add a marker gameobject to represent the downer border of the information gameobject, and move it until it's not visible, but is there a more elegant way?
Any ideas?
For this one, I would use the following trick: use any method (animation, coroutine, Update method...) to move your item out of screen the way you desire. Then you can use the OnBecameInvisible event which is called when the item does not need to be rendered on any camera anymore. The event will there be used to detect that the parent object moved out of screen, and that you want to stop the current movement. You then just need to define in this event that you want to stop the current moving behavior, and you will be done.
void OnBecameInvisible() {
// Stop moving coroutine, moving in Update or current animation.
}
There are probably more elegant ways of doing it as you said, but I think this method should be enough for what you want to achieve.
It took me time, but I found this way for you, attach this script to your gameObject:
public Renderer rend;
//drag the camera to the script in the inspector
public Camera camera1;
Vector3 bottomleft;
Vector3 topright;
void Start()
{
rend = GetComponent<Renderer>();
//the top-right point of the camera bounds
topright= camera1.ViewportToWorldPoint(new Vector3(0, 0, transform.position.z));
//the bottom-left point of the camera bounds
bottomleft = camera1.ViewportToWorldPoint(new Vector3(1, 1, transform.position.z));
StartCoroutine(MoveUp());
}
IEnumerator MoveUp()
{
//while the position and the height are lower that the Y of top right
while (transform.position.y + rend.bounds.size.y < topright.y)
{
//move the object to the new position (move it up)
transform.position = new Vector3(transform.position.x, transform.position.y + .01f, transform.position.z);
//and wait for 1/100 of a second
yield return new WaitForSecondsRealtime(.001f);
}
}
you can play with the WaitForSecondsRealtime value to change the velocity of moving.
I am building a simple pizza slicing game in Unity. I have a Sprite with a collider attached as the pizza, and whenever I drag the mouse over the collider, it gets an enter point and an exit point and draws a transparent line between them, pretty much like this:
The problem is, whenever I move the pizza, the line leaves some sort of trace behind it, even if I disable the line renderer or the whole pizza game object. The only solution I have found for this, is to resize the game window, and everything goes back to normal.
Also, if I play my game in maximized mode, the screen fills with black lines, which is very odd. As before, if I resize my game window everything goes back to normal. Here is a screenshot:
Does anyone have an idea on how to solve this problem? Or, at least, go around it by resizing the game window somehow from the script, during play mode? I already tried resizing the camera and changing the resolution, but it does not change anything.
This is how I draw the lines:
void OnTriggerEnter2D (Collider2D other)
{
enterPoint = LineDrawer.instance.mousePos;
enterPoint.z = 0;
points.Add (enterPoint);
}
void OnTriggerExit2D(Collider2D other)
{
exitPoint = LineDrawer.instance.mousePos;
exitPoint.z = 0;
points.Add (exitPoint);
GameObject obj = new GameObject ();
GameObject instance = Instantiate (obj, transform.position, Quaternion.identity) as GameObject;
Destroy (obj);
instance.transform.SetParent (transform);
instance.name = "Cut";
linerenderer = instance.AddComponent<LineRenderer> ();
linerenderer.material = new Material(Shader.Find("Diffuse"));
linerenderer.useWorldSpace = false;
linerenderer.SetWidth (0.15f, 0.15f);
linerenderer.SetVertexCount (2);
linerenderer.SetPosition (0, enterPoint);
linerenderer.SetPosition (1, exitPoint);
}
The problems that I can see here are:
You should not give Quaternion.identity when you create it. You are making it a child. It should have the same rotation with the parent, or else your local positions won't work:
GameObject instance = Instantiate (obj, transform.position, transform.rotation) as GameObject;
You are not using world space for the line. I bet your enterPoint and exitPoint are in world space. Try this:
linerenderer.SetPosition (0, linerenderer.transform.InverseTransformPoint(enterPoint));
linerenderer.SetPosition (1, linerenderer.transform.InverseTransformPoint(exitPoint));
Why are you doing all this in Trigger functions? There is no if, so these functions execute whenever the pizza hits anything.
I am making my first game in Unity 3D something like tower defense game. I have imported a Fbx model of a tower and attached it to a prefab. Now I want the nozzle of the tower to rotate and follow the enemy as the enemy passes by .
In the fbx model i imported i got I have two poly meshes one for the base of the tower that is fixed, and one for the top of the tower that will rotate. Now I tried to create two different gameObject with these two meshes but if I put them on same point they overlap. So I have to do manual alignment such that the nozzle sit correctly over the base.
I was wondering if there is any other way such that entire towers remain is one gameObject and I can rotate the upper part.
I did manage to solve my problem. Not sure if was the best way , but it works.
To upgrade the towers and transform only the nozzle part I essentially did this.
public class tryFbx : MonoBehaviour {
public GameObject[] ModelPrefab;
GameObject modelInstance;
Renderer rn = new Renderer();
// Attaching the model to prefab at runtime by creating a array of prefabs
public void AttachModelToPrefab(GameObject modelPrefab) {
modelInstance = GameObject.Instantiate(modelPrefab) as GameObject;
modelInstance.transform.position = transform.position;
modelInstance.transform.rotation = transform.rotation;
// Attach the model instance to the prefab shell
modelInstance.transform.parent = gameObject.transform;
}
void Start () {
}
// Update is called once per frame
void Update () {
if (GameManager.upgrade){
AttachModelToPrefab(ModelPrefab[GameManager.towerUpgradeLevel]);
foreach ( Renderer r in modelInstance.GetComponentsInChildren<Renderer>()){
// "polySurface98" is the name of the mesh I want to rotate. The tower and its upgrade have the same name.
if (r.name == "polySurface98")
rn = r;
}
// apply any transformation to the partial fbx
rn.transform.Translate(1,1,1);
}
}
}
You can create a hierarchy of GameObjects; you'll have one parent GameObject representing the tower and 2 children, being that you rotate one of them. Note that the coordinates of the children will be in relation to the parent's, so any "messy" manual calibration you make on the children will be contained.
Or, more complicated, you can create only one mesh that has an animation and apply it to one GameObject.