How to rotate instantiated object to parent - rotation

I have a book case i want to fill with books so i instantiate them and it work perfectly if the bookcase was set to a rotation of (0,0,0)
As soon as i put it in place, at say a rotation of (0,45,0) the books still instantiate in a line not corresponding with the book case im sure it is something i miss please help`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BookPlaceScript : MonoBehaviour
{
public GameObject book;
void Start()
{
float ofsetX = 0.09f;
float ofsetY = 0.18f;
float ofsetZ = 0.08f;
float bookWidth = 0.024f;
for (int i = 0; i < 60; i++)
{
GameObject theBook = Instantiate(book,
new Vector3(transform.position.x + ofsetX,
transform.position.y+ ofsetY,
transform.position.z+ ofsetZ + (i * bookWidth)),
Quaternion.Euler(0,90,0), this.transform) as GameObject;
}
}
}`

Related

WebCam texture doesn't work on Build Windows - Unity 2022.1.17f1

WebCamTexture works fine on editor, but doesn't work on Build. I have tried: turn off antivirus and firewall, check authorization, put the webcamtexture on UI_RawImage and a plane gameObject, nothing works on build. There is no any real conclusion about the same bug on the forums (many are about Vuforia, and I just want to take a photo by a simple webcam on Windows). Any clues? Below the code. Tks in advance.
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using System.Collections.Generic;
// https://stackoverflow.com/questions/24496438/can-i-take-a-photo-in-unity-using-the-devices-camera
public class GetCam2 : MonoBehaviour
{
WebCamTexture webCam;
//string your_path = "D:\\Lixo\\FotosCam";// any path you want to save your image
[SerializeField] string your_path = "";
public RawImage display;
public AspectRatioFitter fit;
public int contadorFotos;
[SerializeField] GameObject planoWeb;
IEnumerator Start()
{
your_path = "" + Application.dataPath;
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam)) {
LigaCamComeco1();
}
}
void LigaCamComeco1() {
if (WebCamTexture.devices.Length == 0)
{
Debug.LogError("can not found any camera!");
return;
}
int index = -1;
for (int i = 0; i < WebCamTexture.devices.Length; i++)
{
if (WebCamTexture.devices[i].name.ToLower().Contains("pc"))
{
Debug.Log("WebCam Name:" + WebCamTexture.devices[i].name + " Webcam Index:" + i);
index = i;
}
}
if (index == -1)
{
Debug.LogError("can not found your camera name!");
return;
}
WebCamDevice device = WebCamTexture.devices[index];
webCam = new WebCamTexture(device.name);
webCam.Play();
display.texture = webCam;
planoWeb.GetComponent<Renderer>().materials[0].mainTexture = webCam;
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.PageUp)) {
Ratio();
callTakePhoto();
}
}
void Ratio() {
float ratio = (float)webCam.width / (float)webCam.height;
fit.aspectRatio = ratio;
float ScaleY = webCam.videoVerticallyMirrored ? -1f : 1f;
display.rectTransform.localScale = new Vector3(1f, ScaleY, 1f);
int orient = -webCam.videoRotationAngle;
display.rectTransform.localEulerAngles = new Vector3(0, 0, orient);
}
public void callTakePhoto() // call this function in button click event
{
StartCoroutine(TakePhoto());
}
IEnumerator TakePhoto() // Start this Coroutine on some button click
{
yield return new WaitForEndOfFrame();
Texture2D photo = new Texture2D(webCam.width, webCam.height);
photo.SetPixels(webCam.GetPixels());
photo.Apply();
byte[] bytes = photo.EncodeToJPG();
File.WriteAllBytes(your_path + "\\ZaxisCam" + contadorFotos + ".jpg", bytes);
contadorFotos++;
}
}
I have tried: turn off antivirus and firewall, check authorization, put the webcamtexture on UI_RawImage and a plane gameObject, nothing works on build.

I am getting the Index was outside the bounds of the array error

I am new to coding in unity and I wrote some code that was giving me the Index was outside the bounds of the array error, but I don't know what the problem is. If you could give me some insight on what I am doing wrong that would be great.This is the code that I wrote for a game that I am working on in unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 20.5f;
public float HorizontalInput;
public float xrange = 16;
public GameObject[] projectileprefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
**//This is the broken line of code**
int ProjectileIndex = Random.Range(0, projectileprefab.Length);
Instantiate(projectileprefab[ProjectileIndex], transform.position, transform.rotation);
}
transform.Translate(Vector3.right * Time.deltaTime * speed * HorizontalInput);
HorizontalInput = Input.GetAxis("Horizontal");
if (transform.position.x < -xrange)
{
transform.position = new Vector3(-xrange, transform.position.y, transform.position.z);
}
if (transform.position.x > xrange)
{
transform.position = new Vector3(xrange, transform.position.y, transform.position.z);
}
}
}
problem is:
int ProjectileIndex = Random.Range(0, projectileprefab.Length);
Instantiate(projectileprefab[ProjectileIndex], transform.position, transform.rotation)
The length of projectileprefab is zero, so it instantiates the first object, but its empty. solution: in the inspector you can set the length of the projectileprefab array and assign game objects to it.

Random Position Spawning

I am currently using the unity tanks game tutorial and have been working on improving it and I am working on having a random tank spawn. It works by choosing a random spawn point for tank 1 and then for tank 2 adds one to the generator to choose the next spawn point so to get rid of the chance of having the same spawn point for both tanks yet both tanks occasionally get the same spawn point. So I was wondering on how to fix this and make the tanks spawn at a random place instead of spawning at the same one
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public int m_NumRoundsToWin = 5;
public float m_StartDelay = 3f;
public float m_EndDelay = 3f;
public CameraControl m_CameraControl;
public Text m_MessageText;
public GameObject m_TankPrefab;
public TankManager[] m_Tanks;
public Transform[] m_SpawnPoints;
private int m_RoundNumber;
private WaitForSeconds m_StartWait;
private WaitForSeconds m_EndWait;
private TankManager m_RoundWinner;
private TankManager m_GameWinner;
private void SpawnAllTanks()
{
int spawn = Random.Range(0, 666);
for (int i = 0; i < m_Tanks.Length; i++)
{
m_Tanks[i].m_SpawnPoint.rotation) as GameObject;
m_Tanks[i].m_Instance =
Instantiate(m_TankPrefab, m_SpawnPoints[(spawn + i) % 6].position, m_Tanks[i].m_SpawnPoint.rotation) as GameObject;
print("Choosing Spawn"+(spawn + i) % 6);
m_Tanks[i].m_PlayerNumber = i + 1;
m_Tanks[i].m_SpawnPoint.position =m_SpawnPoints[(spawn + i) % 6].position;
m_Tanks[i].Setup();
}
}

Why is my for loop looping infinitely

I made two scripts in Unity3D that should check names and count of objects in folder. The thing is, that it is doing it's job infinitely. Don't you know where is the problem?
First Script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MenuSetup : MonoBehaviour {
public static List<Texture2D> UnitIconTextures = new List<Texture2D>();
public static List<string> UnitNames = new List<string>();
public static List<string> UnitPaths = new List<string>();
void OnGUI(){
for(int i = 0; i < UnitNames.Count; i++){
Debug.Log (UnitNames[i]);
}
}
}
Second script
using UnityEngine;
using System.Collections;
public class World : MonoBehaviour {
void Start(){
string path = "Prefabs/Units";
Object[] Units = Resources.LoadAll (path);
if(Units.Length > 0){
for(int i = 0; i < Units.Length; i++){
GameObject unit = Units[i] as GameObject;
Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;
MenuSetup.UnitIconTextures.Add (unitIcon);
MenuSetup.UnitNames.Add (unit.name);
MenuSetup.UnitPaths.Add (path+"/"+unit.name);
}
}
}
}
Ok. Nothing is looping infinitely. The problem is with this code:
void OnGUI(){
for(int i = 0; i < UnitNames.Count; i++){
Debug.Log (UnitNames[i]);
}
}
This method might be called several times per frame. So that's why you see a lot of debug info. While Start method is called only once. So actually, in World the Start method is called once. This method adds all info to MenuSetup class only once. And then you call Debug.Log on every frame.
Read more info about OnGUI on unity doc. Also you should read about Start method here.
Little suggestion
Probably you don't need the if check in
if(Units.Length > 0){
for(int i = 0; i < Units.Length; i++){
GameObject unit = Units[i] as GameObject;
Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;
MenuSetup.UnitIconTextures.Add (unitIcon);
MenuSetup.UnitNames.Add (unit.name);
MenuSetup.UnitPaths.Add (path+"/"+unit.name);
}
}
Because when Units.Length == 0 for-block will not be executed. So probably you want to write
for(int i = 0; i < Units.Length; i++){
GameObject unit = Units[i] as GameObject;
Texture2D unitIcon = unit.GetComponent<Unit>().MenuIcon;
MenuSetup.UnitIconTextures.Add (unitIcon);
MenuSetup.UnitNames.Add (unit.name);
MenuSetup.UnitPaths.Add (path+"/"+unit.name);
}

WP7 tombstoning, saving sprite into Current state not working

I am working on a WP7 game. I am using Game state managment (http://create.msdn.com/en-US/education/catalog/sample/game_state_management , but I think its not important ) I have problem with saving data into
Microsoft.Phone.Shell.PhoneApplicationService.Current.State
if I put there sprite in this method
public override void Deactivate()
{
#if WINDOWS_PHONE
Microsoft.Phone.Shell.PhoneApplicationService.Current.State["Score"] = Score;
Microsoft.Phone.Shell.PhoneApplicationService.Current.State["cloudSprite"] = cloudSprite;
#endif
base.Deactivate();
}
there is nothing in
Microsoft.Phone.Shell.PhoneApplicationService.Current.State
in activate method. However if I remove cloudSprite and put there only Score which is int it works fine. I dont know whats wrong maybe it cant handle more complex objects. I tried also float doubel, it all works. But if I put there something more complex it doesnt work. What do you think ?
EDIT
This is my sprite class. I dont know how to make it serializable. I have added there [DataContractAttribute()] and [DataMember] but its not working
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Runtime.Serialization;
using System.IO;
namespace GameStateManagementSample.GameObjects
{
[DataContractAttribute()]
public class Sprite
{
[DataMember]
public Vector2 Position;
[DataMember]
public Vector2 Size;
[DataMember]
public Texture2D Texture;
[DataMember]
public Rectangle Rect
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, (int)Size.X, (int)Size.Y);
}
}
public Sprite(Vector2 position)
{
Position = position;
}
public Sprite(Vector2 position, Vector2 size)
{
Position = position;
Size = size;
}
public Sprite(Vector2 position, Texture2D texture)
{
Position = position;
Texture = texture;
Size = new Vector2(Texture.Width, Texture.Height);
}
public void LoadContent(string assetName, ContentManager content)
{
Texture = content.Load<Texture2D>(assetName);
if (Size == Vector2.Zero)
Size = new Vector2(Texture.Width, Texture.Height);
}
public virtual void Draw(SpriteBatch spriteBatch)
{
//spriteBatch.Draw(Texture, Rect, Color.White);
spriteBatch.Draw(Texture, Position, Color.White);
}
public virtual void Draw(SpriteBatch spriteBatch, Rectangle TexturePositionInSpriteSheet, Color color)
{
spriteBatch.Draw(Texture, Position, TexturePositionInSpriteSheet, color);
}
public bool Intersects(Vector2 point)
{
if (point.X >= Position.X && point.Y >= Position.Y && point.X <= Position.X + Size.X && point.Y <= Position.Y + Size.Y)
return true;
else return false;
}
public bool Intersects(Rectangle rect)
{
return Rect.Intersects(rect);
}
public static void Serialize(Stream streamObject, object objForSerialization)
{
if (objForSerialization == null || streamObject == null)
return;
DataContractSerializer ser = new DataContractSerializer(objForSerialization.GetType());
ser.WriteObject(streamObject, objForSerialization);
}
public static object Deserialize(Stream streamObject, Type serializedObjectType)
{
if (serializedObjectType == null || streamObject == null)
return null;
DataContractSerializer ser = new DataContractSerializer(serializedObjectType);
return ser.ReadObject(streamObject);
}
}
}
Objects added to the State collection are serialized with the DataContractSerializer. Ensure that anything you're saving there can be serialized that way.
Any serialization errors are silently ignored.
Update
Here's a simplified version of your Sprite object:
[DataContract]
public class Sprite
{
[DataMember]
public Vector2 Position;
[DataMember]
public Vector2 Size;
[DataMember]
public Texture2D Texture;
public Sprite()
{
}
public Sprite(Vector2 position)
{
Position = position;
}
public Sprite(Vector2 position, Vector2 size)
{
Position = position;
Size = size;
}
public Sprite(Vector2 position, Texture2D texture)
{
Position = position;
Texture = texture;
Size = new Vector2(Texture.Width, Texture.Height);
}
}
And here's an example of it being serialized and deserialized:
// Sprite serialization test
var sprite1 = new Sprite(new Vector2(12.34f, 56.78f));
Sprite sprite2;
using (var memStr = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(Sprite));
serializer.WriteObject(memStr, sprite1);
memStr.Position = 0;
var sr = new StreamReader(memStr);
var serialized = sr.ReadToEnd();
// serialized now looks like
// <Sprite xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MiscExperiments"><Position xmlns:d2p1="http://schemas.datacontract.org/2004/07/Microsoft.Xna.Framework"><d2p1:X>12.34</d2p1:X><d2p1:Y>56.78</d2p1:Y></Position><Size xmlns:d2p1="http://schemas.datacontract.org/2004/07/Microsoft.Xna.Framework"><d2p1:X>0</d2p1:X><d2p1:Y>0</d2p1:Y></Size><Texture xmlns:d2p1="http://schemas.datacontract.org/2004/07/Microsoft.Xna.Framework.Graphics" i:nil="true" /></Sprite>
memStr.Position = 0;
sprite2 = (Sprite)serializer.ReadObject(memStr);
// sprite2 now contains the same as
// sprite2.Position = { X:12.34, Y:56.78 }
}
I believe that you get the ArgumentOutOfRangeException which is silently ignored if you aren't debugging (in which case the exception is thrown). The items stored in the State dictionary need to be serializable. Try storing that sprite somehow and saving only a link (source) to the sprite in the state dictionary.

Resources