Add guitext in to gameobject - unity3d

I am working on multiplayer collaboration in unity3d using smartfox server2x . In this there are 2 scripts
a)game manager.cs is drag in to game object and b)timer.js script is drag into guitext . How can i add this guitext into game object? When i am trying to do this iam getting an error like
"There is no 'GUIText' attached to the "Game" game object, but a
script is trying to access it.
You probably need to add a GUIText to the game object "Game". Or your
script needs to check if the component is attached before using it."
This is ma script
#pragma strict
public var timeLeft:float = 10.0f;
public var IsTiming : boolean;
//public bool IsTiming = false;
public function Start () {
//IsTiming = false;
}
function test1(vr1:boolean)
{
IsTiming=true;
Debug.Log("enter33333333333"+IsTiming);
//gamemanager = this.GetComponent("GameManager");
}
function OnGUI()
{
Debug.Log("enter2222222222"+IsTiming);
if(GUI.Button(Rect(0, 70, 150, 25), 'counter'))
{
IsTiming = true;
}
if(IsTiming)
{
Debug.Log("enterzzzzzzzzzz");
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f)
{
guiText.text = "You ran out of time";
guiText.text = "Time is over";
}
else
{
guiText.text = "Time left = " + timeLeft + " seconds";
}
}
}
How can i add this script in to game object "Game".

The error will be happening because your game object does not have a GUIText component; you need to add one first.
To add a GUIText component, you could write gameObject.AddComponent(GUIText) within your Start function.
Or, you could add a GUIText component via the Unity editor menus by going Component > Add..., then type in GUIText.
Also, writing guiText in your script is shorthand for writing GetComponent(GUIText)!

Related

When loading the main menu scene in Unity, I need the player position to reset even if there's a playerprefs save

I need to reset the player's position in the main menu scene to 0,0,0, whether or not they have saved their playerprefs.
This is the code I'm using in Unity to reset the player's position when they exit to the Main Menu scene. This is a VR game. It works for players who haven't saved, but doesn't reset the position of players who have saved their playerprefs, and I don't know how to make that happen.
My reset position script:
//reset position of player in main menu scene
[SerializeField] Transform playerSpawnPosition;
[SerializeField] GameObject player;
[SerializeField] private Camera playerHead;
public void ResetPosition()
{
var rotationAngleY = playerHead.transform.rotation.eulerAngles.y
- playerSpawnPosition.rotation.eulerAngles.y;
player.transform.Rotate(0, -rotationAngleY, 0);
var distanceDifference = playerSpawnPosition.transform.position
- playerHead.transform.position;
player.transform.position += distanceDifference;
}
public void ExitToMainMenu(){
if(pauseMenu == null){
return;
}
pauseMenu.SetActive(false);
if (LeftHand && RightHand)
{
Time.timeScale = 1f;
LeftHand.transform.parent = leftparent;
RightHand.transform.parent = rightParent;
}
SceneManager.LoadScene(0,LoadSceneMode.Single);
ResetPosition();
}
My Save Player Position script:
public void SavePlayerPosition(){
hpc = FindObjectOfType<HVRPlayerController>();
if(hpc == null){
return;
}
PlayerPrefs.SetFloat("PlayerXPos",hpc.transform.position.x);
PlayerPrefs.SetFloat("PlayerYPos",hpc.transform.position.y);
PlayerPrefs.SetFloat("PlayerZPos",hpc.transform.position.z);
Vector3 v = hpc.transform.rotation.eulerAngles;
PlayerPrefs.SetFloat("PlayerYRot",v.y);
PlayerPrefs.SetString("SpawnId", "xyzSave");
Debug.Log("Saved player to position " + hpc.transform.position.x + " "
+ hpc.transform.position.y + " "+ hpc.transform.position.z + " ");
}
public void LoadPlayerPosition(){
hpc = FindObjectOfType<HVRPlayerController>();
if(hpc == null){
return;
}
playerX = PlayerPrefs.GetFloat("PlayerXPos");
playerY = PlayerPrefs.GetFloat("PlayerYPos");
playerZ = PlayerPrefs.GetFloat("PlayerZPos");
playerYRot = PlayerPrefs.GetFloat("PlayerYRot",hpc.transform.rotation.y);
Debug.Log("Loaded player position " + playerX + " "
+ playerY + " "+ playerZ);
}
You're likely calling LoadPlayerPosition() after every position reset. If it's called in a Start() method in a monobehaviour, it's likely going to get called after ResetPosition().
If this is the case, the 0,0,0 values for your players position might not even be set by ResetPosition, instead they're set to the default values returned by PlayerPrefs.GetFloat(), '0.0'.
To Test
Put breakpoints on ResetPosition(); and hpc = FindObjectOfType<HVRPlayerController>();. In the case where a player has set player prefs, I have a feeling your will observe that ResetPosition(); is called before hpc = FindObjectOfType<HVRPlayerController>();.
To Fix
This is a bit tricky. The solution I'd play around with is tying the two functions together in another function call. The function would have a parameter isMainMenuReset. If it's true, call ResetPosition(), else, call LoadPlayerPosition(). You'd have to replace all LoadPlayerPosition() calls in your codebase with this new function call.

material.SetColor doesn't work PC/Android build

This script works as follows: when I raycast an object, it fades out.
Script works great in the Unity Play Mode.
But objects dont wanna fade out on PC/Android build. Just nothing happen, but raycast is detecting object (problem not in raycast)
I debugged Android/PC and script is going into SetMaterialProperties method
Standard material, default new project, default scene, simple capsule gameObject, nothing specific
Because of what could this be?
private IEnumerator FadeIn()
{
Color objectColor = GetComponent<MeshRenderer>().material.color;
while (objectColor.a < 1)
{
float fadeAmount = objectColor.a + (_fadeSpeed * Time.deltaTime);
objectColor = new Color(objectColor.r, objectColor.g, objectColor.b, fadeAmount);
SetMaterialProperties(objectColor);
yield return null;
}
}
private void SetMaterialProperties(Color color)
{
foreach (var material in _materials)
{
material.SetColor("_Color", color);
material.SetFloat("_Mode", 3);
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("_ALPHABLEND_ON");
material.renderQueue = 3000;
}
}

How to add gameobjects via script in the hierarchy in edit mode?

I would like to create a menu item that can build a game object with children and components.
I can't use prefabs for the whole objects because I need that the children are separate prefabs.
You can use something like this:
[MenuItem("YOUR_MENU_NAME/YOUR_SUBMENU_NAME/YOUR_METHOD_NAME %&n")]
static void CreateAPrefab()
{
//Parent
GameObject prefab = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<Object>("Assets/Prefabs/TestPrefab.prefab"));
prefab.name = "TestPrefab";
if(Selection.activeTransform != null)
{
prefab.transform.SetParent(Selection.activeTransform, false);
}
prefab.transform.localPosition = Vector3.zero;
prefab.transform.localEulerAngles = Vector3.zero;
prefab.transform.localScale = Vector3.one;
//Child 1
GameObject prefabChild1 = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<Object>("Assets/Prefabs/TestPrefabChild1.prefab"));
prefabChild1.name = "TestPrefabChild";
prefabChild1.transform.SetParent(prefab.transform, false);
prefabChild1.transform.localPosition = Vector3.zero;
prefabChild1.transform.localEulerAngles = Vector3.zero;
prefabChild1.transform.localScale = Vector3.one;
//Child2...
//...
Selection.activeGameObject = prefab;
}
Don't forget to include using UnityEditor; and to either place the script in an Editor/ folder or use #if UNITY_EDITOR / #endif around the parts using the editor methods. Also I added a shortcut to the MenuItem using %&n (Ctrl + Alt + N).
If you need to change the prefabs that compose the instantiated object, you can try to retrieve them all in your project (maybe be and heavy operation depending on your project) as they did here and display a kind of checklist where you select the prefabs needed as children inside an EditorWindow.

Unity Scripts : Renderer Sprites Component

Im using Inventory system by Brackeys here, then i try to custom an equipment object just like the documentation says. I need that item enable Renderer Sprites component when object drag to weapon holder (inventory), and disable Renderer Sprites when object drag out from weapon holder. I'm implementation GetComponent(SpriteRenderer).enabled = true; for activating Renderer Sprites and GetComponent(SpriteRenderer).enabled = false; to disable, but the script seems don't work, when the object drag out from inventory, Renderer Sprites Component still active. here the part of script for enable/disable Renderer Sprites
#pragma strict
//This script allows you to create equipment effects that will be called either OnEquip or WhileEquipped. This is usefull for magic effects and stat handling.
#script AddComponentMenu ("Inventory/Items/Equipment Effect")
#script RequireComponent(Item)
private var effectActive = false;
function Update ()
{
if (effectActive == true)
{
//-----> THIS IS WHERE YOU INSERT CODE YOU WANT TO EXECUTE AS LONG AS THE ITEM IS EQUIPPED. <-----
}
}
function EquipmentEffectToggle (effectIs : boolean)
{
if (effectIs == true)
{
effectActive = true;
Debug.LogWarning("Remember to insert code for the EquipmentEffect script you have attached to " + transform.name + ".");
//-----> THIS IS WHERE YOU INSERT CODE YOU WANT TO EXECUTE JUST WHEN THE ITEM IS EQUIPPED. <-----
GetComponent(SpriteRenderer).enabled = true;
}
else
{
effectActive = false;
//-----> THIS IS WHERE YOU INSERT CODE YOU WANT TO EXECUTE JUST WHEN THE ITEM IS UNEQUIPPED. <-----
GetComponent(SpriteRenderer).enabled = false;
//Destroy(gameObject);
}
}
is it correct implementation ? what should i do ?
you should read up on collisions and triggers....have them toggle the renderer enabled or disabled in the script.or better yet have the inventories do that....i don't think it's very efficient they way you're trying.
i.e. set the inventories as Triggers and have OnTriggerEnter(collider col) do col.gameObject.GetComponent().enabled = true;
and OnTriggerExit(collider col) do col.gameObject.GetComponent().enabled = false;
if you're using Unity's 2D components then it's OnTriggerEnter2D(Collider2D col) and so on.....
this is just an example and far from 100% fullproof code.just a nudge towards a possible way.you probably need to set some more things.

Dynamically adding 3d objects to a scene in Unity3d

I am working on an Unity3d project in which I want to dynamically add 3d objects to the scene, at the same position, orientation, upon a keyPress. For doing so, I imported these objects and made a prefab for all of these.. I am using the following script to do so.. bt it doesn't do the needfull.. The new object gets instantiated and gets added to the scene but the old objects don't get destroyed. And also ,the position of the new objects is not always the same. The scene consists of a Cube initially. After I press '1' ,'2' etc .. I want a new Object to replace the 1 being displayed (at the same position).
script :
var myCar : GameObject;
var Cube : GameObject;
var Globe: GameObject;
var Clock : GameObject;
var Pistol : GameObject;
var LCD : GameObject;
var prev : int;
var temp: GameObject;
function Start ()
{
prev =0;
temp=null;
}
function Update ()
{
if(prev==0)
temp=Cube;
else if(prev==1)
temp=myCar;
else if(prev==2)
temp=Globe;
else if(prev==3)
temp=Pistol;
else if(prev==4)
temp=Clock;
else if(prev==5)
temp=LCD;
if(Input.GetKey(KeyCode.Alpha1 || KeyCode.Keypad1))
{
if(prev!=1)
{
Instantiate(myCar,temp.transform.position ,temp.transform.rotation);
myCar.transform.localScale = Vector3(0.06,0.06,0.06);
Destroy(temp);
prev=1;
}
}
else if(Input.GetKey(KeyCode.Alpha2 || KeyCode.Keypad2))
{
if(prev!=2)
{
Instantiate(Globe,temp.transform.position ,temp.transform.rotation);
Globe.transform.localScale = Vector3(0.04,0.04,0.04);
Destroy(temp);
prev=2;
}
}
else if(Input.GetKey(KeyCode.Alpha3 || KeyCode.Keypad3))
{
if(prev!=3)
{
Instantiate(Pistol,temp.transform.position ,temp.transform.rotation);
Pistol.transform.localScale = Vector3(0.03,0.03,0.03);
Destroy(temp);
prev =3;
}
}
else if(Input.GetKey(KeyCode.Alpha4 || KeyCode.Keypad4))
{
if(prev!=4)
{
Instantiate(Clock,temp.transform.position ,temp.transform.rotation);
Clock.transform.localScale = Vector3(0.08,0.08,0.08);
Destroy(temp);
prev=4;
}
}
else if(Input.GetKey(KeyCode.Alpha5 || KeyCode.Keypad5))
{
if(prev!=5)
{
Instantiate(LCD,temp.transform.position ,temp.transform.rotation);
LCD.transform.localScale = Vector3(0.04,0.04,0.04);
Destroy(temp);
prev=5;
}
}
}
There are several things to consider:
It would be better to store a reference to the currently active object intead of the if-else-if part.
Destroy is called on the prefab objects but not on the existing GameObject instance and thus doesn't do anything.
The same for all manipulations of transform. They affect the prefabs only.
Not really a bug but really an enhancement: Scale your models in our 3D software so that they can be instantiated without localScale adjusting.
UPDATE: If you don't have access to the original models of the 3D software like Blender, Maya, ... you can easily define the appropriate scale in the prefab. The keypoint is to minimise repeating stuff in your code and to put all kind of property settings into the prefab.
Putting this altogether, my suggestions:
Refine your original models like in 4.
Introduce a member variable to store a reference to the current object.
UPDATE: If you want a special object for example Cube initialised on start, you first drag it into the scene, and then drag the newly created Cube from hierarchy view to the varable current. So you see the cube first when starting the scene and your script knows that this is current when it has to replace it.
Create a method for object instantiation
I'm working in C# but it should be something like
var current : GameObject;
...
function ReplaceObject (prefab : GameObject, newKey : int) {
if (newKey != prev) {
GameObject newObject = Instantiate(prefab, current.transform.position,
current.transform.rotation);
Destroy(current);
current = newObject;
prev = newKey;
}
}
...
function Update ()
{
if(Input.GetKey(KeyCode.Alpha1 || KeyCode.Keypad1)) {
ReplaceObject (myCar, 1);
} else if(Input.GetKey(KeyCode.Alpha2 || KeyCode.Keypad2))
ReplaceObject (Globe, 2);