[C#] Issue with calculating transform.position and Vector2D
Im trying to make a spawner which spawns a line of prefabs depending on the number chosen in the editor. I know that transform.position gives me the current location of the spawner, but I need to add the width of the previous spawned sprite in order to make the line of spawned prefabs.
The issue is that it says I am not allowed to add transform.position with Vector 2D.
What Im trying is: spawnPosition = transform.position + Vector2(0.25, 0);
Answer by Max-Bot · Apr 25, 2016 at 05:05 PM
Use Vector3 instead.
spawnPosition = transform.position + new Vector3(0.25, 0);
And look at Sprite.Bounds (rect) to make sprites sequence accurate: http://docs.unity3d.com/ScriptReference/Sprite-bounds.html
spawnPosition = transform.position + new Vector3(mySprite.bounds.size.x, 0);
I'm trying to make that work, but I am not able to make it work.
Trying to use an array to spawn them consecutively but am not being able to make them work at all.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spawner : $$anonymous$$onoBehaviour {
public int numPlat;
public GameObject[] PlatSpawner;
public GameObject PlatformToSpawn;
public Vector2 spawnPosition;
public Vector2 NextSpawnPosition;
public SpriteRenderer spriteChosen;
// Use this for initialization
void Start () {
Debug.Log("Number" + numPlat);
spawnStuff();
}
// Update is called once per frame
void Update () {
}
private void Awake()
{
}
public void spawnStuff()
{
for (int i = 0; i < numPlat; i++)
{
if (i == 0)
{
PlatSpawner[0] = Instantiate(PlatformToSpawn, transform.position, Quaternion.identity) as GameObject;
}
if (i >= 1)
{
spawnPosition = PlatSpawner[i].transform.position.x + new Vector3( spriteChosen.bounds.size.x,0);
PlatSpawner[i] = Instantiate(PlatformToSpawn, spawnPosition, Quaternion.identity) as GameObject;
Debug.Log("ds");
}
}
}
}
EDIT: Here is the answer to obtain the sprite's witdh : http://stackoverflow.com/questions/23535304/getting-the-width-of-a-sprite.
$$anonymous$$any thanks $$anonymous$$ax Bot!
Your answer
![](https://koobas.hobune.stream/wayback/20220612075607im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
creating a 2d peeling system in unity 0 Answers
Help with Instantiation and Sprite changing lag 0 Answers
Using a reference for another script in a method issue. 0 Answers
Is it possible to create a texture that hides a specific texture? 0 Answers
Error messages with 2d character sprite flipping and movement. 1 Answer