Reputation: 2314
I have the following code for a simple 2d game. The game is lit by a directional light at the moment, which lights both the background and the player.
public class BlockSpawner : MonoBehaviour
{
public GameObject blockPrefab; // a purple cube
public Vector2 spawnSizeMinMax;
private double _secondsBetweenSpawns = 0.5;
private float _nextSpawnTime;
private void Update()
{
if (Time.time > _nextSpawnTime)
{
_nextSpawnTime = (float) (Time.time + _secondsBetweenSpawns);
float spawnSize = Random.Range(spawnSizeMinMax.x, spawnSizeMinMax.y);
Vector3 spawnPosition =
new Vector3(
Random.Range(Player.screenHalfWidth - spawnSize, -Player.screenHalfWidth + spawnSize),
Player.screenHalfHeight + spawnSize,
5
);
GameObject block = Instantiate(blockPrefab, spawnPosition, Quaternion.identity);
block.transform.parent = transform;
block.transform.localScale = Vector2.one * spawnSize;
block.transform.Rotate(new Vector3(0, 0, Random.Range(-20, 20)));
}
}
}
When I drag the prefab onto the scene it appears as a 3d red cube. When I use this code to spawn it, it appears as a 2d black square and does not respond to lighting at all. In every other way it behaves as expected.
Is there some way to make it accept light? I've tried everything in the inspector.
Edit: Here are some screenshots
Upvotes: 1
Views: 63
Reputation: 20269
As you noticed, it's because you have a zero component in the scale. You should calculate the local scale so that no component is zero. You can do this by using Vector3.one
instead of Vector2.one
in your assignment:
block.transform.parent = transform;
block.transform.localScale = Vector3.one * spawnSize;
block.transform.Rotate(new Vector3(0, 0, Random.Range(-20, 20)));
Having a zero-componented scale defies certain assumptions that the lighting calculations have when the engine is determining whether a surface is being hit by light or not.
Upvotes: 1