_id
int64
0
49
text
stringlengths
71
4.19k
0
Using Variable to Reference Different C Script I had a question about using a variable to access different scripts. I have a Rhythm game I'm working on, and I have different scripts named Rudement1, Rudement2, Rudement3, ect... One of my other scripts has something like this, public GameObject HighHatFlare public int RudementNumber TrainingMenuScript.TrainingMenuInt Use this for initialization void Start () Rudement1.NoteCreated Rudement1.NoteCreated 1 What I'm looking to do is use this same script but modify it to to something like this public GameObject HighHatFlare public int RudementNumber TrainingMenuScript.TrainingMenuInt Use this for initialization void Start () Rudement(RudementNumber).NoteCreated Rudement(RudementNumber).NoteCreated 1 The goal is that I can continually use this script and it will modify itself as I use different "Rudement" scripts. I figured it some type of "RudementNumber" or 'RudementNumber', but I can't figure it out. Can someone help me with this? A rudement is a basic sticking pattern that you learn at a very beginning level of drumming. Also spelt "Rudiment" I was always told to spell it with an "e" because of its French roots (not relevant). In this context it could be replaced by the term "level". Each rudiment is a different level and therefore has different amounts of notes. The base script between each level is identical, but the note patterns are different.The script above is attached to each note to give them a numeric order as they are created. It is running under a mono behavior. I think that at it's simplest I'm wondering if you can reference a script name via a changeable string with the intent to pull a variable from it. As the level changes so does this string to pull the amount of NotesCreated from the new level.
0
How can I outline text in Unity? Since it generates more triangles and vertices, the official outline script isn't a good way to do text outlining in my project. How can I outline my text, with better performance? TextMesh Pro may be the solution, but it'll increase the usage of memory heavily and our game is aimed at mobile platforms, so we want to minimise use of memory.
0
Wait for AudioClip finish before destroy Object If I Play the gun sound on my "bullet" object, how can I prevent the end of Audio sound if the bullet hit something so it destroy. To clarify Bullet prefab Audio Source Audio Clip MachineGun.mp3 PlayOnAwake true When I instantiate bullet, MachineGun AudioClip is played. But the bullet is fast and hit something before the clip is end. This Kill the machine audio effect making it irrealistic. How can I tell Unity "Play the sound to the end, despite the object is destroyed". I've tried Destroy(gameObject, AudioClip.length) But it seems not works
0
How to make Sprites scroll with the background image that are inside Scroll View? I'm new in Unity, so I hope you guys can help. I'm developing a 2D game for Android device, on the scene I have a huge background image inside Scroll View (UI Scroll View). Next, I created new empty Game Object "Players", attached to it "Players script" and added "Sprite Renderer" component. From the Sprites I created two prefabs housePrefab and dogPrefab. Inside "Players script" I have the following code SerializeField GameObject housePrefab SerializeField GameObject dogPrefab void Start() var houseXPos 1.41f var houseYPos 2.63f var dogXPos 0.41f var dogYPos 2.63f GameObject house Instantiate(housePrefab, transform.position new Vector2(houseXPos, houseYPos), Quaternion.identity) as GameObject GameObject dog Instantiate(dogPrefab, transform.position new Vector2(dogXPos, dogYPos), Quaternion.identity) as GameObject After I run game both Sprites appears on the screen (as I expected). The problem occurs when I Scroll background image, both sprites stay in the same position under scrolling. In other words sprites not scrolling with the background image. As far as I understand, the Sprites needs to be added to the background image, but I don t know how to do it. How to make Sprites scroll with the background image? Thanks to all in advance.
0
When when pressing on the G key one of parts is scaling slower then the other? Each Prefab is built with canvas and two panels childs of the canvas. I'm scaling the two panels. The automatic mode part is working fine. The problem is with the G key. When I press once on G it's scaling both panels up to maxSize then when pressing on G once again it's scaling the panels back down to minSize. But when I press on G quick in the middle while it's scaling them it should turn the scaling side in the middle. For example if I press G and both panels start scaling to maxSize if in the middle I press on G again it should scale them both to minSize without getting first to the maxSize. But in this case one of panels is keep scaling to maxSize a bit and then move back to minSize. But they both should turn side in the middle at once. It seems like one of them have a lag he turn sides a bit after the first one. using System.Collections using System.Collections.Generic using UnityEngine public class Scaling MonoBehaviour public GameObject Prefab public int numberOf 1 public float duration 1f public Vector3 minSize public Vector3 maxSize public bool scaleUp false public Coroutine scaleCoroutine public bool automatic false public bool coroutineIsRunning false private List lt GameObject gt parts new List lt GameObject gt () private void Start() for (int i 0 i lt numberOf i ) GameObject objecttest Instantiate(Prefab) foreach (Transform child in objecttest.transform) parts.Add(child.gameObject) private void Update() if (automatic) if (!coroutineIsRunning) Scale() else if (Input.GetKeyDown(KeyCode.G)) Scale() private void Scale() scaleUp !scaleUp if (scaleCoroutine ! null) StopCoroutine(scaleCoroutine) for (int i 0 i lt parts.Count i ) if (scaleUp) scaleCoroutine StartCoroutine(ScaleOverTime(parts i , maxSize, duration)) else scaleCoroutine StartCoroutine(ScaleOverTime(parts i , minSize, duration)) private IEnumerator ScaleOverTime(GameObject targetObj, Vector3 toScale, float duration) float counter 0 Vector3 startScaleSize targetObj.transform.localScale coroutineIsRunning true while (counter lt duration) counter Time.deltaTime targetObj.transform.localScale Vector3.Lerp(startScaleSize, toScale, counter duration) if (counter gt duration) coroutineIsRunning false yield return null
0
Unity Engine Move the Object According to Image tracking Motive Want to develop Software which will track the Pad and move the four views of object accordingly. What I did Current Knowledge I had placed the four camera around the object and change their viewport accordingly. Then, using Vuforia, tracked the pad(Image). Problem As I am beginner in Unity. I don't know how to move the object as the pad moves i.e. i don't want AR Projection on pad. but i want to use pad to move the object. You can see my progress and work i done in these images. http imgur.com a V5brG Thanks.
0
How do I work around the "You are missing the recommended JDK" error? After switching to 2019.4 LTS I got this error (using Windows 10) You are missing the recommended JDK. Install the recommended version using Unity Hub. I installed the JDK using Unity Hub many times now, still the same error. Tho I don't think it's getting installed. As you can see below, the quot OpenJDK quot checkbox remains blue no matter how many I try to install it. When I tried downloading and installing the JDK (JDK 1.8.0 181) myself I get this error instead You are missing the recommended JDK, versions other than 1.8.0 are not officially supported.
0
Simplyfing dissolving octree to simple boxes by adjacent octants with similar traits I am looking forward to create a navigation volume to be utilized by AI actors. The approach I am trying to tackle here is to first generate an octree and associate with respectable flags data (type, what's contained for now). The octree is going to be fairly deep (up to 0.1 units). This is the scene I am using for testing purposes results in 1947817 nodes in 9 levels. (22 x 9 x 22) I am looking for an algorithm concept pseudo code that would transform this octree into non uniform, axis aligned boxes derived from octants that match certain flags data, that would, for instance, help me determine the navigation volume similar to what can be seen here (Havok) With "I am looking for" I have a feeling of such an algorithm concept already existing, though, I am not sure. The feeling drives me towards this being a fairly mathematical problem that resides behind a common name. The other approach would be to utilize a non uniform grid (creates 4356000 cells) for the detailed shape to then be expanded (simplified) down to some boxes. Which my feeling tells, would utilize the same algorithm. As for the "what have you tried part" well... I have googled for some time with various combinations from keywords grid, merge, cell, flags, occupied, gamedev, octant, grow, largest space, adjacent and maybe some others to no avail. Well, before pushing the Post button, I did try some more keywords and ended up with this answer https gis.stackexchange.com questions 23365 how to combine adjacent polygons sharing similar trait into single polygon which appears to be close to what I am looking for, except that it's 2D (though, I gave the keyword "polygon" for this query). Having learned that the process is called "dissolve", I made some more attempts with various combos with added word "dissolve". And through my findings some more searches and so on... Well... nothing. If the answer wont yield any results, I know that I could attempt this by raying the hell out of the graph by starting at either corner and flooding through it all, basically, brute forcing my way. So... Is the common algorithm concept already out there, that I could be pointed towards? or what guidelines should I follow to produce such a product?
0
Can't open scripts in Unity 2019.2.11.f1 version I'm using Visual Studio 2017, Unity Hub to 2.1.3 and just created a project using Unity's 2019.2.11.f1 version. Once trying to open a script in Unity, it doesn't open and then I'm forced to use Task Manager to End Unity's task because can't even close it normally due to not being able to interact with the screen. No errors or warnings, VS doesn't open, can't interact with Unity anymore. This doesn't block me from working, it just isn't as convenient as before.
0
How can I unpack texture data following a 16 8 bit pattern? Is possible to unpack texture data following a specific bit packing scheme? I have read that texture data in HLSL can be read in as 4 floats of 32 bits each totaling 128 bits. The packing scheme I'm looking to use is 16 packing groups of 8 bits each. I am having trouble figuring out how to unpack this data without loss due to it being interpreted as floats.
0
How can I rearrange layers in Unity 2D? I'm new to using Unity (2019.30a2) and am currently learning by watching Brackey's (youtube) "How to make a 2D Game in Unity" At 6 58 he is able to rearrange his layers easily. On my hand, I can create but am unable to change the order of the layers. Looking at other questions on similar subjects hasn't provided me with a solution yet. I'm currently working around it but feel this will hinder me in the future. The screenshot of the unmovable layers is included below
0
How to save persist a GameObject with incremental levels? Dictionary? List? I create buildings and they have child Text objects that will reflect the building level. The Problem What can I use to store the buildings a player has built so the data can be persisted? I've looked at Lists, but when I upgrade a building, how would I update the list so that particular building has its new level reflected? I'm working on a dictionary so I can update the key with the new value (level) but running into a problem with the keys and names. If I have lets say 10 "Farms" and try to add them to the dictionary, even though they have different properties, I get an error that I have a duplicate. Currently I am learning how to persist that data through scenes GameManager.CS public class GameManager MonoBehaviour public static Dictionary lt Building, int gt playerBuilt new Dictionary lt Building, int gt () public void SaveState() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " EmpireGame", FileMode.Open) SaveClass sc new SaveClass() food Player.food.amount, buildingList playerBuilt bf.Serialize(file, sc) file.Close() Serializable class SaveClass public int food, wood, iron, stone public Dictionary lt Building, int gt buildingList new Dictionary lt Building, int gt () Building.CS public abstract class Building MonoBehaviour, IUpgradable public int ID level this building is public Text levelText public int level 0 starting cost to amplify the upgrade cost public int foodBase, woodBase, ironBase, stoneBase Upgrade cost public int foodCost, woodCost, ironCost, stoneCost public float BuildingCostPercentage 5f public void UpdateDictionary() if (GameManager.playerBuilt.ContainsKey(this)) GameManager.playerBuilt this level else GameManager.playerBuilt.Add(this, level) Note I have not tested the save function so I expect errors.
0
Throwing a grabbed object I'm trying to throw the carried object in the direction of the first person controller, but unable to make it. I could make the carried object drop, but the same time i need to instantiate velocity to the carried object, so that i could forward. I'm building up a bowling game and trying to make the ball behave like the same when the player throws the ball. It should hit the alley and move forward to hit the pins. Below is what so far I've tried. using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera public GameObject empty bool carrying public GameObject carriedObject Camera cam public float distances public float smooth float speed 1000f Use this for initialization void Start() cam GameObject.Find("MainCamera").GetComponent lt Camera gt () mainCamera GameObject.FindWithTag("MainCamera") Update is called once per frame void Update () if (carrying) carry(carriedObject) CheckDrop() else pickup() private void pickup() if(Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if(Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if(p! null) carrying true carriedObject p.gameObject void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void ThrowBall() GameObject go (GameObject)Instantiate(carriedObject,transform.forward, Quaternion.identity) pickupable to go.GetComponent lt pickupable gt () to.Throw(carriedObject.transform.forward speed) void CheckDrop() if(Input.GetKeyDown(KeyCode.U)) Drop() void Drop() carrying false carriedObject Instantiate(carriedObject, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation) carriedObject.GetComponent lt Rigidbody gt ().isKinematic false gameObject.GetComponent lt Rigidbody gt ().AddForce(carriedObject.transform.forward 100) carriedObject.GetComponent lt Rigidbody gt ().AddForce(0,0,1f) carriedObject.gameObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject null Thanks in advance!
0
Endless runner character stops moving unexpectedly I've been trying to make an endless runner game in Unity in which a player moves forward automatically and can move from x to y axis while still moving forward. I do not know how to program so I used a Template. Since then, my player stops moving forward when there is no box collider in front of it. it stops when there is a box collider by the sides and even when it's at the front. It's really frustrating. Below is the script I used using System.Collections using System.Collections.Generic using UnityEngine public class NewPlayerScript MonoBehaviour private CharacterController controller private Vector3 direction public float forwardSpeed public float maxSpeed private int desiredLane 1 public float laneDistance 4 public float jumpForce public float Gravity 20 void Start() controller GetComponent lt CharacterController gt () Update is called once per frame void Update() direction.z forwardSpeed if (controller.isGrounded) if(forwardSpeed lt maxSpeed) forwardSpeed 0.1f Time.deltaTime direction.y 1 if (Input.GetKeyDown(KeyCode.UpArrow)) Jump() else direction.y Gravity Time.deltaTime if (Input.GetKeyDown(KeyCode.RightArrow)) desiredLane if (desiredLane 3) desiredLane 2 if (Input.GetKeyDown(KeyCode.LeftArrow)) desiredLane if (desiredLane 1) desiredLane 0 Vector3 targetPosition transform.position.z transform.forward transform.position.y transform.up if (desiredLane 0) targetPosition Vector3.left laneDistance else if(desiredLane 2) targetPosition Vector3.right laneDistance transform.position Vector3.Lerp(transform.position, targetPosition, 80 Time.deltaTime) private void FixedUpdate() controller.Move(direction Time.fixedDeltaTime) private void Jump() direction.y jumpForce I really dont know what the problem is. I have the character controller and the sphere collider enabled in my inspector for my character and I have only the box collider enabled for my prefabs.
0
Unity Passing an array in a shader I want to pass my array (which is inside my c code) to my shader. Shader "custom shader4" Properties myArray("Array", Float 256 ) SubShader Pass CGPROGRAM public float myArray 256 code... this is obviously not working. Is anyone here who knows how to solve this? (also in c ) myMaterial.MyArray anotherArray It has to be something like this right? Or do I need a workaround?
0
Unity Script and game not syncing after player respawn I have a health system for my player that looks like this public int fallBoundary 10 public int Health public int numOfHearts public Image hearts public Sprite fullHeart public Sprite emptyHeart void Update() if(Health gt numOfHearts) Health script works, why does heart display not? Health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt Health) hearts i .sprite fullHeart else hearts i .sprite emptyHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false Unfortunately, after respawn, the hearts do not sync anymore. My debugging showed, that the elements of hearts still did their job, resetted and got replaced correctly. However, in my game, nothing changes after the respawn (should reset to full health and change if player gets damaged). For the respawn, I am loading my prefab, which I also checked (everything is there). To avoid confusion my hearts never reset to 0, but stay at 1. Player Prefab that loads during respawn Hearts after respawn
0
Unity Text Mesh Pro can not get referenced in VSCode I am using Text Mesh Pro in my Unity 2019.3.4f. The TMP works fine in unity, but in the code editor, Visual Studio Code, the TMP related things are marked with red wave underline, which means the VSCode could not get the reference of TMP. In my csproj file, the TMP reference exists, here are some related codes lt ProjectReference Include quot Unity.TextMeshPro.csproj quot gt lt Project gt e8ae9ed6 ed86 3de7 e777 7e6794b003b2 lt Project gt lt Name gt Unity.TextMeshPro lt Name gt ProjectReference Include quot Unity.TextMeshPro.Editor.csproj quot gt lt Project gt af8771c0 66d3 f01a 48b5 78951bce8a23 lt Project gt lt Name gt Unity.TextMeshPro.Editor lt Name gt My TMP works fine in every aspects, but there are code warnings in the VScode, quot could not fine the namespace of TMPro quot . Is there anyone know how to fix it?
0
Deleting an item in the game world detecting if an item supports other items I'm writing a 3D construction module similar to the how you build houses in the Sims. Users are able to build walls and floors (which also act as ceilings) on multiple floors (layers). This question needs a little background info I'm not using an physics, there is no gravity. I use the term floor ceiling tile here interchangeably. Essentially all are floor tiles, ceiling tiles are just floor tiles on a higher layer. I store the build data in a multi dimensional array like grid layer row column position The layer represents the layer (ground floor, 1st floor etc..). The row and columns make up the grid. The position can hold any number of 3 positional values, namely 0 wall on west side of cell 1 wall on south side of cell 2 ceiling So for example, a south wall on the row column 2 4 on layer 3 would looks like grid 3 2 4 0 gt null,1 gt item,2 gt null This works great, and it's easy to write functionality to check if a item can be placed at any position (by looking at neighbouring cells, layers below etc...) Here is the actual problem and question I'm writing functionality to delete items within the game world. The rules by which I decide if something can be deleted are what you would expect in real life Any item that's not on the ground floor needs something else supporting it So for the following examples Only 1 of the 2 blue tiles adjacent to the red tile could be deleted The red tile cannot be deleted because the wall connected to it would no longer have a support. Walls are simple enough, I just check nothing is in the same row col above them (since it would only be another wall or ceiling). It's the floor ceiling tiles that are difficult. It's easy enough to check if an item has neighbouring items, or if is supported by a wall below, but I can't seem to find an efficient way to do the checks if, for example, a ceiling tile has many neighbouring tiles that it supports VS those same neighbouring tiles, but they are supported by another item I thought maybe I should be storing the information about which other items support the current item during placement, but that just feels like moving the same complexity to another part of the code. Is there and algorithm or concept that I could use adapt to do the checks?
0
Transparent alpha mode in Shader Graph creates unwanted jagged outline I am currently working on a transparent shader and noticed that all my works have a jagged dark outline. I guess I've used the wrong settings somewhere, but I've been fiddling around with a couple settings without any success. I have created a basic shader, which shows the shader settings I use and the problem. It might be a little hard to see on the screenshot, so please have a look in full resolution. There's a small black outline around the circle on the yellow background.
0
Combining Rotation, Jump, and Crouch Animations with 2D Blend Tree I have a 2D Freeform Blend Tree that I'm using to animate a character that can currently Walk Sprint Forward Walk Sprint Backward Strafe Sprint Strafe Left Strafe Sprint Strafe Right Idle My goal is to add in rotation, jump, crouch, and quot firing when walking quot animations. In just dealing with turning or even jumping for now, I understand how to handle and call the animations in the code, but not sure of how it should be set up in the animator. Do I transition to rotation jump animations on the base layer? I'm reserved doing it this way because I lose the ability to blend and take advantage of those transitions. Can I build it into my current 2D blend tree even though the blend tree is only X and Z axis? public class twoDControllerMovement MonoBehaviour Animator animator public CharacterController controller SerializeField private float walkSpeed 12.0f SerializeField private float strafeSpeed 10.0f SerializeField private float sprintMultipler 2.0f SerializeField private float rotationSpeed 120.0f Start is called before the first frame update void Start() animator GetComponent lt Animator gt () controller GetComponent lt CharacterController gt () Update is called once per frame void Update() handle sprint float currentWalkSpeed walkSpeed float currentStrafeSpeed strafeSpeed bool runPressed false handle shift if (Input.GetKey(KeyCode.LeftShift)) currentWalkSpeed walkSpeed sprintMultipler currentStrafeSpeed strafeSpeed sprintMultipler runPressed true calculate movement float strafe Input.GetAxis( quot Strafe quot ) currentStrafeSpeed Time.deltaTime float translation Input.GetAxis( quot Vertical quot ) currentWalkSpeed Time.deltaTime float rotation Input.GetAxis( quot Horizontal quot ) rotationSpeed Time.deltaTime execute movement transform.Translate(strafe, 0f, translation) transform.Rotate(0, rotation, 0f) handle movement animations if (runPressed) animator.SetFloat( quot VelocityZ quot , Input.GetAxis( quot Vertical quot ) sprintMultipler) animator.SetFloat( quot VelocityX quot , Input.GetAxis( quot Strafe quot ) sprintMultipler) else animator.SetFloat( quot VelocityZ quot , Input.GetAxis( quot Vertical quot )) animator.SetFloat( quot VelocityX quot , Input.GetAxis( quot Strafe quot )) handle roration animations if (Input.GetAxis( quot Horizontal quot ) lt 0.1f) Debug.Log(Input.GetAxis( quot Horizontal quot )) else if (Input.GetAxis( quot Horizontal quot ) gt 0.1f) Debug.Log(Input.GetAxis( quot Horizontal quot )) Also open to any feedback on improving the code above, my goal is as small and clean as possible! I do have a slight delay in animations starting when switching directions that I have to work out at some point and would eventually.
0
How to make two connected rigidbodies pull each other? I'm making a game in Unity where a ship can connect to a rock in space, and drag it. Both are Rigidbody2D. I want the ship to be affected by the rock like this If I drag the rock, then stop the ship, the rock keeps moving with the velocity it had. If the rock gets pulled away by something, it should drag the ship when the rope is fully extended. If the rock is heavy, the ship has more trouble pulling it The rope might be a little elastic to make it more appealing Is there a joint like this, or should I manually code it so they can affect each other? It seems like a basic game physics thing, but I can't find anything about it. I tried using a distance joint with quot Max Distance only quot for this, but it doesn't work, as the rock stops when the ship stops For the visual part, I'm using verlet integration, with a slight gravity on the rope to make it more quot springy quot , the current is a little too much but that's finetuning and not the problem of this question. )
0
How to make wall tiles overlap floor tiles a bit in Unity3D? Currently my tiles are very strictly placed, there are wall tiles, and floor tiles, and they don't overlap at all. What I want to achieve is to have my walls overlap my floors a bit. So their inner edges doesn't have to be a stright line, but a free shape, with "transparent holes" which show the floor below. Resulting in a much better feeling. My current approach is to have multiple layers. One for the floor and wall (single) tiles), and one above this, which will have the overlapping, decorative parts of the walls. But this methods feels slow and clunky For one wall tile I have to place 9 tiles tileparts to make it look nice. (the tile itself plus the neighbours). It would be better to place just one tile which got overlapping parts
0
How to restrict an AssetReference to a specific type? I am using the Addressables package of Unity. I am trying to restrict an AssetReference type in the Unity inspector to a specific type. Currently a user can assign any Unity object to an AssetReference, but I would like to guide the user to assign the correct types to the correct variables and (if possible) filter the assets type list to include only the assignable types when the user click on the drop down arrow According to the Unity documentation https docs.unity3d.com Packages com.unity.addressables 1.6 api UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute.html it seems like there is some sort of annotation available. The documentation is very limited and I have tried UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute(type typeof(PlayerMaster)) public UnityEngine.AddressableAssets.AssetReference playerMaster but it made no difference. I also tried to create my own AssetReference type Serializable public class Reference UnityEngine.AddressableAssets.AssetReferenceT lt PlayerMaster gt , UnityEngine.AddressableAssets.IKeyEvaluator public Reference(string guid) base(guid) but with this new type I cannot select anything! The following code snippet at least seems to restrict the list to GameObjects which is an improvement, but the user can still assign the wrong GameObjects easily. I was hoping for a more strict filter, but if it is not possible I will settle with public UnityEngine.AddressableAssets.AssetReferenceGameObject playerMaster
0
Removing the billing permision from a apk build in unity So recently we made a version of our game that is paid and not free. This of course means that we removed both ads and IAP capabilities. Now I'm sure that I have removed every single peice of code that references ads or IAP from scripts that get built into the apk but Unity still keeps adding the billing permision to the manifest. Apart from exporting a google android project and then modifying the manifest and then buidilng to apk what other options do I have to solve this ?
0
Anchor a health bar to a character enemy I have a game I'm working on where the player can see the health bars of the player's avatar and other creatures in the game. I want this health bar to always follow the character creature around. However, I can't figure out how to do this. I thought having the position change when the respective object moved would do the trick, but apparently, it doesn't. When watching the health bar's transform, however, it shows that it is moving with it's respective object but I don't see it on the game screen. Can anyone explain how I go about accomplishing this? Here's the Dropbox link to the project. HealthBar Script public class EnemyHealthBar MonoBehaviour public Texture2D healthBar public Texture2D health public Rect healthBarPosition public Rect healthPosition public GameObject monster void Start() void Update() transform.position new Vector3(monster.transform.position.x, monster.transform.position.y, monster.transform.position.z) Debug.Log(transform.position) void OnGUI() GUI.DrawTexture(healthBarPosition, healthBar) Video of what's currently happening Dropbox Link
0
How to predict where the soccer ball should be intercepted by an AI player after being kicked? This question has been asked many times before, but most of the answers give solution to the problem where ball (target) is assumed to be moving at a constant velocity. In my scenario, I'm making a football game. When I kick the ball into a direction by applying some force to the ball's rigidbody, I want a second AI player to find the point in the ball's path where he can intercept the ball. Now this ball can keep slowing down per frame, it does not keep moving with a constant speed. I have attached an image for visualisation. I know the ball's position, ball's current velocity, AI player's position, AI player's constant speed. How do I find such a point, where AI player can intercept the ball? I am able to calculate such a point with the current velocity of the ball, but that point is not accurate, and changes as ball's current velocity changes per frame, as the ball can keep slowing down after every frame. This makes the AI player act kind of like a homing missile. Instead, I want the AI player to predict a point and just run to it. Here's the C (Unity) Code I have till now public Vector3 CalculateIntercept() Vector3 pos Ball.GetInstance().transform.position Vector3 dir Ball.GetInstance().GetVelocity() dir.y transform.position.y float dist (pos transform.position).magnitude return pos (dist 6.17f) dir 6.17 is the AI player's constant speed. There's no drag on the ball, but there is a physics material with friction. I suppose to solve this, I might need to account for acceleration maybe. Please help me figure this out. Thanks!
0
Place tiles along a specific axis direction I want to be able to place tiles only in the direction I've started quot drawing quot them. For an example, if I click and hold on tile at position (0,0), and start dragging to the right, I only want to select or draw on coordinates (1,0), (2,0), (3,0) and so on. However, for the next tile, if I point my mouse at the tile (4,1), I only want (4,0) to be selected, aka, ignore the Y changes because I'm currently placing on the X axis. What would be a good and clean way to do this? I've tried doing this but not only does it not work well, my code is very bloated because I'm not good at this logic that requires more math than usual. Here's what I tried (needless to say it's very messy and didn't work properly) private bool isSelecting private Vector3Int selectionDirection Vector3Int.zero public List lt Vector3Int gt selectedPositions new List lt Vector3Int gt () private SelectDirect selectDirect if (Mouse.current.leftButton.wasPressedThisFrame) if (UIManager.IsMouseOverUI()) return Vector3Int gridPosition Map.GetGridPosFromMousePos() if (Map.IsInsideMap(gridPosition)) if (!selectedPositions.Contains(gridPosition)) selectedPositions.Add(gridPosition) isSelecting true if (Mouse.current.leftButton.wasReleasedThisFrame) isSelecting false selectedPositions.Clear() selectionDirection Vector3Int.zero selectDirect SelectDirect.None if (isSelecting) if (selectionDirection Vector3Int.zero amp amp selectedPositions.Count 2) selectionDirection selectedPositions 1 selectedPositions 0 if (Mathf.Abs(selectionDirection.x) Mathf.Abs(selectionDirection.y) gt 1) isSelecting false selectedPositions.Clear() selectionDirection Vector3Int.zero selectDirect SelectDirect.None return if (selectionDirection.x 1) selectDirect SelectDirect.Right else selectDirect SelectDirect.Up Debug.Log(selectDirect) Vector3Int gridPosition Map.GetGridPosFromMousePos() if (Map.IsInsideMap(gridPosition)) switch (selectDirect) case SelectDirect.None if (!selectedPositions.Contains(gridPosition)) selectedPositions.Add(gridPosition) break case SelectDirect.Right if (gridPosition.x selectedPositions selectedPositions.Count 1 .x Mathf.Abs(selectionDirection.x) amp amp !selectedPositions.Contains(gridPosition)) selectedPositions.Add(gridPosition) break case SelectDirect.Up if (gridPosition.y selectedPositions selectedPositions.Count 1 .y Mathf.Abs(selectionDirection.y) amp amp !selectedPositions.Contains(gridPosition)) selectedPositions.Add(gridPosition) break
0
Why is transform.up behaving differently for different functions? Can anyone please explain to me what i'm doing wrong here? As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and lineRenderer.SetPosition(1, transform.up maximumBeamLength) using UnityEngine RequireComponent(typeof(LineRenderer)) public class LaserBeam MonoBehaviour SerializeField private float maximumBeamLength 5f private LineRenderer lineRenderer private void Start() lineRenderer GetComponent lt LineRenderer gt () void Update() lineRenderer.SetPosition(0, transform.position) RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up) Debug.DrawLine(transform.position, transform.up maximumBeamLength, Color.blue) Debug.DrawLine(transform.position, transform.up , Color.red) if (hit.collider) lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z)) else lineRenderer.SetPosition(1, transform.up maximumBeamLength)
0
problem with git on a unity project I tried to version control my project folder with git. When it came to pull the project from the repository, though, something went wrong apparently scripts are missing and the prefabs and kind of all the graphical elements appear to be pinkish. Does anybody know how to fix this? This is the .gitignore I'm using at the moment Temp Obj UnityGenerated Library ExportedObj .svd .userprefs .csproj .pidb .suo .sln .user .unityproj .booproj .DS Store .DS Store? . .Spotlight V100 .Trashes Icon? ehthumbs.db Thumbs.db Thanks in advance.
0
How to force a translation to go through an exact point? I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them. The problem here is that in my code void Update() if (scoreholder.CheckScore() lt scoretimer) if the current score is less than set X score if (killcam.transform.position.y quadholder.y) and if the camera's position equals the position of the generic quad PROBLEM HERE killcam.GetComponent lt cameraUp gt ().SetCam (true) stop the cam while (scoreholder.CheckScore () lt scoretimer) do stuff offset mr.material.mainTextureOffset offset.y offsetSpeed 0.1f mr.material.mainTextureOffset offset break else once the score is not less than the desired X score, move the cam killcam.GetComponent lt cameraUp gt ().SetCam (false) So my problem here is that this line of code if (killcam.transform.position.y quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use gt instead of , but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping. I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.
0
fading from one scene to another not working I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425 344 that I downloaded from Google. How can I solve this issue? Fading.cs (I added this to an empty game object) public Texture2D fadeOutTexture public float fadeSpeed 0.8f private int drawDepth 1000 private float alpha 1.0f private int fadeDir 1 void onGUI () alpha fadeDir fadeSpeed Time.deltaTime alpha Mathf.Clamp01(alpha) GUI.color new Color (GUI.color.g, GUI.color.b, alpha) GUI.depth drawDepth GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture) public float BeginFade (int direction) fadeDir direction return (fadeSpeed) void onLevelWasLoaded() BeginFade ( 1) In the script of the trigger object IEnumerator gameScene2() float fadeTime GameObject.Find ("FadeObject").GetComponent lt Fading gt ().BeginFade(1) yield return new WaitForSeconds(fadeTime) Application.LoadLevel("Scene2") These are the image settings for the black .png image
0
Cannot use DLL in my Unity project I'm pretty new in Unity and i'm trying to write reusable code to use across multiple "project". So I wrote this class to POST and GET highscore via WebRequest. I compiled the project to a DLL and added the DLL in my assets folder, and then I created a test script added to a GameObject opened it in VS2013 and created a reference to the DLL in the Assets folder, and now im trying to use it and it keep saying that the class name doesnt exist.
0
How to always land a square box in 90 degree How can i Always Land a box in 90 degree Here What i want Here what i don't want public Rigidbody2D boxRb public float jumpSpeed public Vector3 rotation public float rotationSpeed public bool rotationEnabled public float gravityMultiplier void FixedUpdate() if (Input.GetMouseButtonDown(0)) boxRb.velocity jumpSpeed Vector2.up if (rotationEnabled true) transform.Rotate(rotation rotationSpeed Time.deltaTime) if (Input.GetMouseButtonDown(1)) boxRb.velocity Vector2.up Physics2D.gravity.y (gravityMultiplier 1) Time.deltaTime void OnCollisionEnter2D(Collision2D collision) rotationEnabled false Debug.Log("Collided") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX transform.Rotate(0, 0, 90f) void OnCollisionStay2D(Collision2D collision) rotationEnabled false Debug.Log("In collison") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX void OnCollisionExit2D(Collision2D collision) rotationEnabled true Debug.Log("Free") rotationSpeed 10f
0
get access to Transform of a Clone in Unity In my game when you lose, A panel with a button on it appears and if you don't have enough coins, You may be directed to shop by hitting shop button. when buying is completed you can return to the scene from where you left it and resume the game. I'm using PlayerPrefs to save properties like slider.value my player position timescale etc, But I can't access to Transform of an Instantiated GameObject (Clone). it acts like obstacle and is Instantiated continuously. Here is my script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using CodeStage.AntiCheat.ObscuredTypes using CodeStage.AntiCheat.Detectors public class Spawner5 MonoBehaviour public float maxTime 1 public float Timer 0 public GameObject pipe public float height Use this for initialization void Start () pipe GameObject.FindGameObjectWithTag ( quot Gear quot ) Update is called once per frame void Update () if (Timer gt maxTime) GameObject newpipe Instantiate (pipe) newpipe.transform.position transform.position new Vector3(4, Random.Range ( height, height) ,0) Destroy (newpipe, 15) Timer 0 Timer Time.deltaTime
0
Is Unity's Random seeded automatically? I seem to recall Unity's Random is automatically seeded checking the documentation it doesn't say it outright, but a certain interpretation of their words might seem to imply it. The seed is normally set from some arbitrary value like the system clock before the random number functions are used. This prevents the same run of values from occurring each time a game is played and thus avoids predictable gameplay. However, it is sometimes useful to produce the same run of pseudo random values on demand by setting the seed yourself. (emphasis added)
0
How to make score counter independent of framerate I have a score counter, but I've noticed that the lower the framerate is, the slower it counts. How can I make it so it ignores the framerate? using System.Collections using UnityEngine using UnityEngine.UI public class Score MonoBehaviour private Text scoreText private static int score private static int finalScore private static bool count public static int scoreMultiplier private void Start() scoreText GetComponent lt Text gt () count false scoreMultiplier 1 public static void StartCounting() count true public static void StopCounting() count false public static void Reset() count false score 0 public static IEnumerator MultiplyBy(int scoreMultiplier) Score.scoreMultiplier scoreMultiplier yield return new WaitForSeconds(6f) Score.scoreMultiplier 1 private void Update() if (count) score scoreMultiplier Slice the score so the number doesn't get too big finalScore score 4 scoreText.text finalScore.ToString("00000") Edit Fixed by adding Time.deltaTime and putting it in FixedUpdate instead of Update private void FixedUpdate() if (count) score scorePerSecond Time.deltaTime scoreMultiplier finalScore Convert.ToInt32(score) scoreText.text finalScore.ToString("000000")
0
How to check if a specific instance of a prefab is pressed? This one is hard to explain, so I'll show the code first for (var i 0 i lt Input.touchCount i) if (Input.GetTouch(i).phase TouchPhase.Began) Ray ray Camera.main.ScreenPointToRay(Input.GetTouch(i).position) RaycastHit2D hit Physics2D.Raycast(ray.origin, ray.direction) if (hit) clicksNeeded 1 GetComponentInChildren lt TextMesh gt ().text "" clicksNeeded Debug.Log(clicksNeeded) print("was a hit") I need to check if hit touches the specific game object that the script is linked to, as at the moment if any of the circles are clicked, clicksneeded 1 to all objects currently instantiated. Thanks for the help!
0
Finding enemy object in player's forward direction within a range I would like to know the way by which I can find enemy objects tagged with "player" in a forward direction within a range say 3 units from the player.
0
How to programmatically change sprite sheet sub sprite name I am trying to change the name of the sub sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time. Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity. I am attempting to change the sub sprite names programmatically. I tried using AssetDatabase.RenameAsset (...) on the sprite sheet asset, which only changes the sprite sheet name and not sub sprites. I then thought to obtain a sub sprite and attempt to change its name using the below code. if (AssetDatabase.IsSubAsset (subSprite)) AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" i.ToString ()) However, this too only changes the sprite sheet name. I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub sprite names. I also tried changing subSprite.name, but this just changes the internal name and not the asset name. Any ideas?
0
(Unity) Physics based movement vs Straight position change Unity provides a cool physics engine for game development and I want to utilize it in my game. Shorter version I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want move x units per second. If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous am I wrong? Longer version The following description is where I use "physics", why I need physics engine. In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall. A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move. But doing so(adding force to the direction I want to move) will result in truck like slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture. However problem is not over yet, you must consider a situation where you change direction of movement while the character is running. If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement burn velocity by adding backward force. Thus rotation burns velocity. So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity. This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position. But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position?
0
Programming logic to 2D point and click adventure puzzle? I am totally new to game development. I want to create a 2D Puzzle Adventure point and click game similar to like 'Rooms' but scenes are connected. I have already done the inventory system but currently lack the functionality to be used with an object in a scene. My question is how do I approach creating a system that will take in dynamic number of events? For example, I have key that will unlock the door, and the next scene I want to use it again without pre programming this action specifically. I want to approach this in an efficient way so that I can use the system again for future games similar to this. Can someone give me an idea because I am really stuck at this point. I don't want to program the game assigning individual scripts to each objects but rather do this systematically. I am using Unity and C
0
How can I avoid updating my Unity projects when I have two versions installed? I currently have two versions of Unity on my Windows computer. I would like to not update my projects to avoid compatibility issues like I had in the past. Installation in another folder goes just fine, but when I try to open Unity, it says that another Project is already opened and that if I want to continue I must update it. If I close this window, Unity aborts as well. Is there a way to avoid this behaviour?
0
Managing draw calls for customized materials when targeting mobile I want to know how to minimize draw calls when rendering multiple customized characters onscreen, presumably with 3 4 materials apiece. Is there a better way to achieve custom color configurations than instancing duplicating materials? Am I overthinking the problem? Our game is a frenetic, goofy arena fighter, made in Unity. We plan to publish on mobile, first. I am tasked with creating an art pipeline which allows for customizable additions and color changes to the player's avatar. I'm trying to look ahead to when this character creator will be a part of the game and consider the performance implications of this kind of system. A character creator could potentially serve us in the generation of random NPCs at launch, and will feature heavily when we move to multiplayer. My concern is with the number of draw calls on mobile. Currently, we have a bunch of identical characters, all creating instances of the main material on spawn to differentiate by random color. Since draw calls are directly linked to the number of materials onscreen, this process concerns me. Before complicating the issue with variations in mesh and texture on a per object basis, having 1 material per character already limits us to a certain number of NPCs onscreen. I delivered a material solution which allows changing one color to differentiate from other characters. Now the director is asking about the feasibility of breaking each character into multiple materials to allow for player customization. With 4 materials per character (1 shared), draw calls would increase geometrically per spawn. I've heard mobile platforms tend to be limited to about 20 120 draw calls between low and high end devices. That would make for 5 35 characters allowed onscreen at once, assuming we could get the environment down to around 5 draw calls. I would be especially interested in any material masking techniques people are aware of. Having a need for around 4 customizable aspects would seem to point towards using some sort of RGBA texturing and masking solution, but I have no idea how to make Unity do that.
0
Unity Profiling Mesh.Bake PhysX CollisionData Doubling CPU cycles I have a mob that, when it dies, spawns smaller versions of itself. When this happens there's a huge resource spike. The profiler narrowed it down to baking the meshes of the new objects. I have a couple of smaller questions related to this, but the crux of the issue is that it looks like the baking is occurring twice (doubling CPU usage) as shown below in both Instantiate and Transform.SetParent. I'd normally say it's redundant, but in every way it looks like it's happening twice and take over one full second total. Why would this happen twice on the same set of object (there are a variable number of spawned mobs, so the actual numbers can vary)? As an aside, can this be backed in the prefab somehow to avoid this?
0
Unity plane that is normal to Z axis I want to create a plane that will be normal to the Z axis, but I am having difficulty visualizing what rotation it needs to have. I want to have a top down view upon the plane such that I can use the X and Y coordinate system for position, and the Z axis for height. It seems intuitive for me to point the camera in the same rotation as this plane, and give it an orthogonal view and a positive Z value (and set gravity to have a negative Z value), but I seem to be fighting against the grain and running into more issues than I should be, so I would like to ask what rotations I should be using for this. What rotation should I use for the plane? can the camera share the same rotation? (assuming I want the top to be y and the right to be x as seen from the camera.
0
Is it possible to use one if statement for each level scene? I'm working on a platform game where you as a player have to collect logs, to keep on all the fires in the level. Each campfire has a timer, which ensures that every x number of seconds the animation of the fire is changed to a numb fire. The timer of a campfire is blocked by the script, when the player has received the fire at 100 . When all fires are 100 you won, if not you lose. Know I use the following if statement to check if the player has won or lose if (Application.loadedLevelName "Level 0") if (campfireAmount allCampfireFull) Do something print ("level 1 complete") Application.LoadLevel (6) if (campfireAmount allCampfireEmpty) Do something print ("level 1 failed") Application.LoadLevel ("GameOver") What I searching for is how I can make this if statement useful for each level, whiteout use for each level scene above if statement. Beside that, what I want is that after each level you get a win scene (if possible a reusable scene) and after clicking in that scene on a button, you should go to the next level scene. Is there a way to load the next level, whiteout set a hard number of the rang list of "Build Settings"?
0
How can I call Schedule() on interface that inherits from IJob So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual) public interface IMesherJob IJob VoxelDataVolume lt byte gt VoxelData get set NativeArray lt MeshingVertexData gt OutputVertices get set NativeArray lt ushort gt OutputTriangles get set One example of a meshing job is marching cubes, which looks like this public struct MarchingCubesJob IMesherJob So here's my question If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it This works MarchingCubesJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) But this does not work IMesherJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) I noticed that Schedule() is an extension method for T where T struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob
0
Why there is no isGrounded and Move properties for the CharacterController? using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(CharacterController)) public class SC FPSController MonoBehaviour public float walkingSpeed 7.5f public float runningSpeed 11.5f public float jumpSpeed 8.0f public float gravity 20.0f public Camera playerCamera public float lookSpeed 2.0f public float lookXLimit 45.0f CharacterController characterController Vector3 moveDirection Vector3.zero float rotationX 0 HideInInspector public bool canMove true void Start() characterController GetComponent lt CharacterController gt () Lock cursor Cursor.lockState CursorLockMode.Locked Cursor.visible false void Update() We are grounded, so recalculate move direction based on axes Vector3 forward transform.TransformDirection(Vector3.forward) Vector3 right transform.TransformDirection(Vector3.right) Press Left Shift to run bool isRunning Input.GetKey(KeyCode.LeftShift) float curSpeedX canMove ? (isRunning ? runningSpeed walkingSpeed) Input.GetAxis("Vertical") 0 float curSpeedY canMove ? (isRunning ? runningSpeed walkingSpeed) Input.GetAxis("Horizontal") 0 float movementDirectionY moveDirection.y moveDirection (forward curSpeedX) (right curSpeedY) if (Input.GetButton("Jump") amp amp canMove amp amp characterController.isGrounded) moveDirection.y jumpSpeed else moveDirection.y movementDirectionY Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below when the moveDirection is multiplied by deltaTime). This is because gravity should be applied as an acceleration (ms 2) if (!characterController.isGrounded) moveDirection.y gravity Time.deltaTime Move the controller characterController.Move(moveDirection Time.deltaTime) Player and Camera rotation if (canMove) rotationX Input.GetAxis("Mouse Y") lookSpeed rotationX Mathf.Clamp(rotationX, lookXLimit, lookXLimit) playerCamera.transform.localRotation Quaternion.Euler(rotationX, 0, 0) transform.rotation Quaternion.Euler(0, Input.GetAxis("Mouse X") lookSpeed, 0) On both I'm getting the same error 'CharacterController' does not contain a definition for 'isGrounded' and no accessible extension method 'isGrounded' accepting a first argument of type 'CharacterController' could be found (are you missing a using directive or an assembly reference?)
0
Error when using GetComponent (Object reference not set to an instance of an object) I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following NullReferenceException Object reference not set to an instance of an object DebugCombo.Update() (at Assets DebugCombo.js 9) which points to the text.text assignment. This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js) pragma strict public class DebugCombo extends MonoBehaviour function Update () var text gameObject.GetComponent(TextMesh) var combo gameObject.GetComponent(Combo) text.text quot Current quot Time.time quot Limit quot combo.comboTime How do I get rid of this error?
0
How to tween to move an object in arc? Okay, so I think I need to use a tween in order to move an object in my game. I have some little green dudes that need to move in an arc (bezier) to a location that is clicked by the user. My game functions by having the mouse point raycast to the screen giving my character a position to move to. They don't just run though, they fire off their jetpacks and should travel in an arc to the target position. I'm pretty new to Unity but all I can come up with is using a tween to do this. Am I missing something? That being said, I'm totally confused on what a tween actually is. I can't wrap my head around how the object can be moved outside of an update function. I'm using the "free from the asset store" LeanTween package. I feel like there should be some sort of easier way to achieve the desired behavior. How can I have my character move from Vector3 A to Vector3 B in an arc?
0
How can I create a dice toss that results in a specific value? I am trying to create a 3D dice for a game. Normal dice has been created by setting cube for dice with Rigidbody and apply force to throw a dice. Now the problem is, the user wants to give a value 1 6 in the text box then they will press the roll button. The dice have to rotate and need to show the dice value as the user enters in the text field once it stops rolling. For example In the Input box the value entered as 5, Now the dice want to roll on the table and show the value as 5. Anyone, please help me to solve this Thanks in Advance
0
Changing texture offset in unity by script I am trying to change texture offset in a material by a script to create a parallax effect, but it doesn't move a bit no matter what I am trying. Any tips for this case? Or am I missing something?
0
How to create button prompts for interactable objects in Unity? I have a class of objects tagged as interactables that my player can interact with when within range. When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.). I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn. If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed. Any advice on how to go about achieving this? I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet. You can be as general or as specific as you'd like in your answer.
0
Symbol not found Error in Unity3d IOS Buid in Xcode I new to IOS build , when i try to build following error showing I using Unity 5.2.1f1 and Xcode 7.0.1(7A1001) . Previous unity version was 5.0.1 , in that version , same error was found thats why i updated unity , even though same error is existing When i taking build Xcode showing "Buid Succeeded" , when running on simulator , following error is showing . Warning Error creating LLDB target at path ' Users UserName Library Developer Xcode DerivedData Unity iPhone dzxhzbvzarcxwncwpymwfynqdipi Build Products Release iphonesimulator GameName.app' using an empty LLDB target which can cause slow memory reads from remote devices. dyld Symbol not found assignIdentifiersAndCallbackGameObject Referenced from Users UserName Library Developer CoreSimulator Devices 400B12B2 B711 453C B0E3 7DDF12A770F0 data Containers Bundle Application E62986EE 618C 4530 B5F8 A09D43162DBD GameName.app GameName Expected in flat namespace in Users UserName Library Developer CoreSimulator Devices 400B12B2 B711 453C B0E3 7DDF12A770F0 data Containers Bundle Application E62986EE 618C 4530 B5F8 A09D43162DBD GameName.app GameName (lldb) please help me , how to solve this problem
0
Game 30 done on HTML5. Maybe it was a bad idea. Should I change to Unity3d? I'm creating a 3d game on HTML5. It's 30 complete and the hard part is already coded. The server is on node.js.Now I'm realizing that maybe it was not a wise choice. This is because I realized Three.js still has many bugs. I don't see the same thing on every machine. Each browser, OS, can give different results. I'm afraid my clients will have a great stress installing my game properly. I have tons of sprites and models on my game. I wonder if my clients will have to load all them again everytime they want to play? I wonder if a Node.js server will be fast enough to handle it, and I'm afraid it won't be scalable. What would you advise me? Should I continue and finish the game on HTML5 or is it better to remake it on something else, like Unity3d for the client and (what?) for the server?
0
objects are keep falling I added some screenshots above. When I run the game obstacle are falling rapidly through y axis. So, there's no more obstacle in that ground. If there's ground than those obstacle should stopped. I tried by freezing them. But, when another object hit them they are froze. So, I want ground to stop them. I have another question also. I have player movement. When I will run the program. The Player should be go through z axis. But, The object(player) don't move. PlayerMovement.cs using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 2000f void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(!Input.touchSupported) Still support PC keys if(Input.GetKey(KeyCode.D)) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey(KeyCode.A)) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) else For touch devices if(Input.touchCount 1) var touch Input.GetTouch(0) var touchPos touch.position var isRight touchPos.x gt Screen.width 2f if(isRight) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(Physics.Raycast(transform.position,Vector3.down,0.5f) false) rb.velocity new Vector3(0, rb.velocity.y, 0) rb.constraints RigidbodyConstraints.FreezePositionZ else rb.constraints RigidbodyConstraints.None if(rb.position.y lt 1f) FindObjectOfType lt GameManager gt ().EndGame() PlayerCollision.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() else if(collisionInfo.collider.name quot END quot ) FindObjectOfType lt GameManager gt ().CompleteLevel() void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) If you look at above source code clearly. So, you might see that I have a Debug.Log right there. But, when I run the game. I don't get any message to console. As a new game developer(learning) I don't know what's happening, what's wrong with this.
0
All sides shadow outline in Unity NGUI How can I make such exactly the same shadow using NGUI?
0
Build includes sprite packer atlas and its original textures I use Unity's Sprite Packer, it's working great. However, when I looked at the build report (in the Editor.log) it turns out that the build often includes the generated atlas texture and its original textures too. It wastes too much space. I checked the size of the unzipped APK and the build report was correct. I tried several configurations (adding and removing textures) but I could not find any regularities. Some observations I could reproduce this only if I use 25 textures in an atlas with variable sizes. Texture compression settings did not matter. Packer policy could modify the result but did not solve the problem. Has anybody had similar experience? I can upload my test project if necessary.
0
SpriteRenderer color not responding to script! I have written a simple c class that is supposed to change the color of the Player Renderer. But, there seems to be a problem! whenever I call the function OnCallFun() ... the color stays put and does not change. I have looked into the solution for quite some time now but no hope. does anyone have a solution? using UnityEngine public class ChangeColor MonoBehaviour Reference to Sprite Renderer component private Renderer rend SerializeField private Color colorToTurnTo Color.white Use this for initialization void Start() rend GetComponent lt Renderer gt () Change sprite color to selected color rend.material.SetColor( quot SpecColor quot , colorToTurnTo)
0
Tree batching problem in Unity I have some problems with batching trees. I'm using the default unity terrain system and trees. My problem is that trees won't get batched together (I've set up static, dynamic, and GPU instancing) and as I've inspected the frame debugger I've come to these results I used trees with the optimized bark material and optimized leaf material What causes distinct draw call 1 Wind 2 color and size variations for trees draw call reason non instanced properties set for instanced shader if I remove Wind or variations the GPU instancing would work (I don't want to remove wind and variations), Is there any way to batch trees in this case?
0
Unity Rotate a point around an arbitrary axis and anchor I'm trying to find out the point which is already rotated. To solve this I did a Rotation, save the position, set the previous position and return my position, like this Vector3 rotatePointAroundAxis(float angle ,Vector3 axis, Vector3 anchor) Vector3 oldPosition gameobject.transform.position gameobject.transform.RotateAround(gameobject.GetComponent lt HingeJoint gt ().anchor, gameobject.GetComponent lt HingeJoint gt ().axis, angle) Vector3 newPosition gameobject.transform.position gameobject.transform.position oldPosition return newPosition I searched already. And I found very hard solutions. http inside.mines.edu fs home gmurray ArbitraryAxisRotation by the way i dont think I understand this, it seems like too much. Is there any way to change that function to a "simple" one, so I don't need to rotate things forth and back to get the coordinates? EDIT I believe tranform.RotateAround() takes the position and rotation from the transform parameters and calculates the solution and changes the current position and rotation of the gameobject. So the solution should take 5 parameters current position of the unrotated Object current rotation of the unrotated Object the point the Object should be able to pass the rotation axis the angle and return 2 parameters the rotated objects new rotation the rotated objects new position
0
Why the update function only call once I asked about this question How to efficiently implement a 7 segment display? in previous post. Now I just add an update function to the last part of the code to display the time(I don't bother the exact time at the moment just want to make sure the number change regularly). However,I'm not sure why the update only run once, I checked the answer in this website, mentioned the root cause is gameobject deactivated(Update function only running once) but this is not my case. I tried with void OnMouseDown() Display(DateTime.Now.Second) , the number does change according to my mouse button so I'm not sure what wrong with Update function. In addition, I assigned all the variable but it still pop out message unassigned reference exception, not sure where the problem. using System using UnityEngine public class ClockDigit MonoBehaviour Assuming you number your segments as follows 0 5 1 6 4 2 3 Store a lookup table for which segments should be active when displaying each digit. static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 activeColour Color.red public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour else segments i .color inactiveColour public void Update() Display(DateTime.Now.Second) I tried this command also, the infinite loop freeze the Unity and FixedUpdate() command also update the frame only one time. void Update() while(true) Display(DateTime.Now.Second)
0
Outputting Unity commandline build log to console? I'm using Blue Ocean to do a Unity3D build through command lines (https docs.unity3d.com Manual CommandLineArguments.html). I currently have a stage in blue ocean which runs the build command in a 'Windows Batch Script' outputting the log to a text file on the computer. is there a way to also output that same logging text to the blue ocean build output? Right now all I see is the batch command. One way to accomplish this would be if the build output was sent to the console instead of just the logfile passed in the argument.
0
NavMeshAgent Do something once destination is reached I have items on the ground which I can pick up. If I'm within the radius of a trigger collider around the item, I just pick it up. If i'm not, I want to set my NavMeshAgent's destination to the item and then pick it up once I've arrived. I have done this exact thing before but have since completely forgotten how to do it. The way picking up an item occurs is by clicking on its UI nameplate, not the physical item gameObject. Therefore, I'm using the OnPointerClick function. If possible I'd like to not have to check every frame whether I have arrived at my destination or not, but I'm open to doing it that way for now. I'm not really familiar with how the NavMeshAgent API works. I would think that if (!agent.pathPending amp amp agent.remainingDistance lt agent.stoppingDistance) or something similar would work. I'm kind of lost though, any help is appreciated. void Update() if (!navMeshagent.pathPending amp amp navMeshagent.remainingDistance lt navMeshagent.stoppingDistance) PickUpItem() public void OnPointerClick(PointerEventData eventData) if (itemPickupRange.playerIsInRange) PickUpItem() else navMeshAgent.SetDestination(item.transform.position) This doesn't work. I've tried breaking up the conditions in Update and making it a nested loop, and it still doesn't work. One other thing there's some weird behaviour with remainingDistance. Sometimes It's a number between 0 and 1 when I'm positive that the actual distance must be much larger.
0
How to detect speed on collision The problem with OnCollisionEnter2d is that it only gets called when there is a collision but what I wanted is to get the current speed of object at the moment of impact until the object stops moving. So that I if the object stops moving after impact I will call another function. void OnCollisionEnter2d(Collision2D collision) Debug.Log(speed) problem this will only give the speed at the moment of impact if(speed lt 0) blah blah I also tried putting speed variable on the Update() void Update() var currentVelocity player rb.velocity speed currentVelocity.magnitude
0
Unity Asset Store Tools Problem So I downloaded Asset Store Tools in the Unity Asset Store. When I upload my asset to my package, I get this popup Wrong project path The path selected must be inside the currently active project. Note that the AssetStoreTools folder is removed automatically before the package enters the asset store. My Unity is version 5.4.0b25. I've tried other assets and reinstalled Unity, I still get the same popup. Screenshot
0
Not able to connect to Photon(PUN).photon unity networking error I'm new to photon Networking. My game was working great suddenly this is appearing Cannot send messages when not connected. Either connect to Photon OR use offline mode! UnityEngine.Debug LogError(Object)
0
In Unity, how can I register a custom file type that is always opened with my game? I want my players to be able to create their own scenes as custom levels, save them as files (say custom1.gamelevel), and open them directly in my game program by double clicking the level file, rather than having to go through the steps of opening the game, browsing to the file in my menus, and then loading that scene level. I already have loading custom levels covered. I just need a way to associate this custom file type with my game which can open it. I am mainly interested in a Windows based solution. How can I do this?
0
How do I make function on user clicked on close button Ads reward? So I'm here want to make function when the user closed the Ads before video ads end, the function is stopping or revert, in this case, I'm using ienumerator methods, but I don't know how to add the handler on Ads, because I already using HandleRewardClosed method not like I want but because its same with user watch the vid till end not closed the videos before ended . public void loadRewardVideo() rewardedAd.LoadAd(new AdRequest.Builder().Build(), rewarded Ad ID) rewardedAd.OnAdLoaded HandleRewardedAdLoaded rewardedAd.OnAdClosed HandleRewardedAdClosed rewardedAd.OnAdOpening HandleRewardedAdOpening rewardedAd.OnAdFailedToLoad HandleRewardedAdFailedToLoad rewardedAd.OnAdRewarded HandleUserEarnedReward rewardedAd.OnAdLeavingApplication HandleOnRewardAdleavingApp rewarded video events public event EventHandler lt EventArgs gt OnAdLoaded public event EventHandler lt AdFailedToLoadEventArgs gt OnAdFailedToLoad public event EventHandler lt EventArgs gt OnAdOpening public event EventHandler lt EventArgs gt OnAdStarted public event EventHandler lt EventArgs gt OnAdClosed public event EventHandler lt Reward gt OnAdRewarded public event EventHandler lt EventArgs gt OnAdLeavingApplication public event EventHandler lt EventArgs gt OnAdCompleted Rewared events public void HandleRewardedAdLoaded(object sender, EventArgs args) Debug.Log( quot Video Loaded quot ) public void HandleRewardedAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) Debug.Log( quot Video not loaded quot ) public void HandleRewardedAdOpening(object sender, EventArgs args) Debug.Log( quot Video Loading quot ) public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args) Debug.Log( quot Video Loading failed quot ) public void HandleRewardedAdClosed(object sender, EventArgs args) Debug.Log( quot Video Loading failed quot ) StartCoroutine(ClosedAds()) IEnumerator ClosedAds() GameManager.instance.isGameOver true yield return new WaitForSeconds(.05f) GameManager.instance.isStarted false Time.timeScale 0 FirebaseRemoteConfig.instance.DisplayAds() GameManager.instance.ShowingGameOverPanel() GameManager.instance.pauseBtn.SetActive(false)
0
How to properly write "stick to surface" character logic that handles unexpected large time deltas? I've been trying to wrap my head around this issue in a 2D platformer game (but this may as well apply to 3D games) I want the character to "stick" to the surface that it's moving along and at the same time maintain the same velocity no matter the incline decline of the current surface. Also, if my character's speed is 1 unit sec and the current delta time is 0.25, I want it to travel exactly 0.25 units no matter the "shape" of the surface met along the way during the frame. Naively, I started with this base logic (warning, pseudo code incoming) vel acceleration timeDelta movementDelta vel timeDelta hit raycast(pos, downward) if (hit) vectorAlongSurface hit.normal fancyLinearAlgebra pos vectorAlongSurface.Normalized movementDelta.Magnitude else pos movementDelta But this is correct only if my character moves along the same surface normal for the whole frame and it breaks pretty badly if during the frame the surface has different normals along the way. This can give the feeling that the speed at which the character is moving is inconsistent. To give you an example While I do expect answers like "just don't make your terrain like that" I'm also considering situations where my game might experience an unexpected lag and have to deal with a large time delta that might push the character through different surface normals during the same frame. Any advice on how to properly handle this would be much appreciated. I was thinking about somehow tracing all the changes of surface inclination from the character's position to the "naive raycast hit" point, but that seems to be quite expensive, especially considering that all the enemy characters would have to do the same. There must be some simple solution to this that I'm not seeing. Or maybe there's a way to make the inconsistency of speed in the given example less noticeable irrelevant? Thank you guys.
0
Get the position of a GUI.Button and instantiate in its position I am trying to instantiate a GUI.Box in the position of my GUI.Button when it is clicked but I just cant seem to get the position of the button. The button does change position. Here is the code of my button in my Editor script void OnGUI () GUI.Button(new Rect (5,95, 300, 100), "Hello")
0
Questions about Jrpg NPC events (Unity C ) So, I'm trying to wrap my head around something. I've got my basic quest system up and running for my rpg style game. Right now I'm taking a look at NPC events and triggers that as I see it have two distinct styles The classic floor panel trigger that rpg maker uses or have a listener class for quest active event active My questions are thusly what's the best way to go about activating the event and what's a good way to define the event? Like set movement patterns etc would it be feasible in json? Or should I use scriptable objects?
0
Instantiate works fine in Editor and does not work after building game Here is the situation, In my project everything works fine. After I build the game for windows, the prefab does not instantiate. I don't know which part I missed. This is how I load the prefab from Resources folder private void Awake() areaButtonPrefab Resources.Load lt GameObject gt ( quot Prefabs AreaButton1 quot ) And this is how I instantiate prefab for each data in a List public void SetAreaToUI() foreach (var j in areaList) cloneItem Instantiate(areaButtonPrefab, originalRect.position, new Quaternion(0, 0, 0, 0), rect) TMP Text text cloneItem.GetComponentInChildren lt TMP Text gt () AreaButtonData buttData cloneItem.GetComponent lt AreaButtonData gt () buttData.area j text.text j.areaName cloneItem.SetActive(true) cloneItems.Add(cloneItem)
0
How do I make a game object appear on the other side when it leaves the screen? I'm doing an assignment for a course and what's required is to include a moving asteroid in the game that starts moving in a random direction and when the asteroid leaves the bottom of the game window it should re appear at the top of the game window ,so I wrote the script for warping and I applied it to the asteroid and a ship in my game ,then built it to WebGl game. the warping worked fine in the editor for both the ship and the asteroid, while it only worked for the ship in the built game, and I can't figure out what's wrong this is the script (ScreenUtils gives the borders of the screen) float Radius void Start () Radius GetComponent lt CircleCollider2D gt ().radius void OnBecameInvisible() Make the ship wrap Vector3 position transform.position if (position.x Radius gt ScreenUtils.ScreenRight position.x Radius lt ScreenUtils.ScreenLeft) position.x 1 if (position.y Radius gt ScreenUtils.ScreenTop position.y Radius lt ScreenUtils.ScreenBottom) position.y 1 transform.position position
0
Procedural mesh comes out black in any shader I wrote a script that Creates a mesh procedurally mr gameObject.AddComponent lt MeshRenderer gt () mf gameObject.AddComponent lt MeshFilter gt () mf.mesh new Mesh vertices GetVertices(), triangles GetTriangles() uvs UpdateUVMap() assign material shader. mr.sharedMaterial new Material( Shader.Find( quot Shader Graphs surface quot ) ) (the mesh is a sphere for this example) I created my Shader in shader graph (any shader seems to have the same result) When played, all seems good except that the object is black. What's happening? basic uv map example from docs public Vector2 UpdateUVMap() Vector2 uv new Vector2 this.vertices.Count for (int i 0 i lt uv.Length i ) uv i new Vector2(vertices i .x, vertices i .z) return uvs.ToArray() uvs.Clear() uvs.AddRange(uv)
0
Unity Shader Make water on terrain transparent without fading I want to create a shader for a terrain to make the water fully transparent but not invisible or faded. In this example I would want the purple square to be seen through water but not through the land. I want the water to look exactly the same as before. I want objects underneath the terrain to be visible through the water. I already have a shader to make objects underneath the water look like they are seen through water. I want to use a single camera as I would need a slow script on each of the cameras.
0
Why am I getting errors like these when trying to build my app I am currently trying to build and publish my app to the universal windows platform halfway through the process of doing so, during the validation process I got stopped with these errors. The 1st one I am clueless to what I can even do and the second one I don't know why is happening. Please help. First error Supported API test FAILED Supported APIs Error Found The supported APIs test detected the following errors API D3D12GetDebugInterface in d3d12.dll is not supported for this application type. UnityPlayer.dll calls this API. Impact if not fixed Using an API that is not part of the Windows SDK for Windows Store apps violates the Windows Store certification requirements. How to fix Review the error messages to identify the API that is not part of the Windows SDK for Windows Store apps. Please note, apps that are built in a debug configuration or without .NET Native enabled (where applicable) can fail this test as these environments may pull in unsupported APIs. Retest your app in a release configuration, and with .NET Native enabled if applicable. See the link below for more information Alternatives to Windows APIs in Windows Store apps. Second error App resources FAILED Branding Error Found The branding validation test encountered the following errors Image file SplashScreen.scale 200.png is a default image. Impact if not fixed Windows Store apps are expected to be complete and fully functional. Apps using the default images e.g. from templates or SDK samples present a poor user experience and cannot be easily identified in the store catalog. How to fix Replace default images with something more distinct and representative of your app. Here is the full output for further details 1.1.1.0 App Architecture x64 Kit Version 10.0.16299.15 OS Version Microsoft Windows 10 Pro (10.0.16299.0) OS Architecture x64 Deployment and launch tests PASSED Bytecode generation PASSED Background tasks cancelation handler PASSED Platform version launch PASSED App launch PASSED Crashes and hangs Package compliance test PASSED Application count PASSED App manifest PASSED Bundle manifest PASSED Package size PASSED Restricted namespace Windows security features test PASSED Binary analyzer PASSED Banned file analyzer PASSED Private code signing ... (error 1 above) App manifest resources tests PASSED ... (error 2 above) Debug configuration test PASSED Debug configuration File encoding test PASSED UTF 8 file encoding App Capabilities test PASSED Special use capabilities Windows Runtime metadata validation PASSED ExclusiveTo attribute PASSED Type location PASSED Type name case sensitivity PASSED Type name correctness PASSED General metadata correctness PASSED Properties Package sanity test PASSED Platform appropriate files PASSED Supported directory structure check Resource Usage Test PASSED WinJS background task
0
How can I stop Substance's runtime texture caching? Procedural textures with the Substance Engine seem to update very quickly if you turn off caching, modify one exposed variable at a time, modify it frequently, and even then only after you've attempted to modify it 2 or 3 times. However, I want basically the opposite. For example, units have a "blood" variable that generates blood differently on them as they take damage, as well as a "battle wear" variable that generates scratches and dents, but doesn't revert when they heal. So to force a variable not to cache, I have to set it to some dummy value, then back to normal, then call RebuildTexturesImmediately. How can I tell Substance not to cache a variable at runtime, so I can change it once and have the texture regenerate quickly?
0
Prefab instatiation not going well I'm trying to Instantiate a prefab when the mouse goes over collider of some GameObject so I'm using OnMouseEnter to instantiate and will use OnMouseExit to destroy it after (when this part of code works fine), the problem is that no error appears in the console but the prefab are not being instantiated, does not appear in the inspector or in the scene, even so, when I print it's name in the console (last line), it appears right. Is my syntax correct? void OnMouseEnter () string nomeSeta "SETA" direcao.getNome () GameObject seta Resources.Load lt GameObject gt (nomeSeta) float pontosXeZ Util CalculosGeometricos.ObterPontosCentraisXeZDeUmRetanguloPorNumeracaoSemRotacao (terrenoPai, direcao.getCoeficienteHorario ()) seta.transform.localPosition new Vector3 (pontosXeZ 0 , 0.0f, pontosXeZ 1 ) seta.name nomeSeta print ("seta.name " seta.name)
0
Getting user id from one scene then to the next scene I'm new to multiplayer and photon so pardon me if this question is somewhat frequent. I have successfully set up my project to start from a main menu waiting room actual gameplay scene. However I couldn't search my way through getting a sort of user id from waiting room(ie order of user joined to waiting room) then use it in the gameplay scene to manipulate sort by score by hp etc. Perhaps I got the while concept of having to identify unique players via such variable? I'm not quite sure. I just got my foot in the multiplayer development realm, so please go easy on me. Edit Sorry for my initial question being quite vague. Basically, I'm trying to replicate this with Photon. I've got various things set up but was stuck at where designating individual players to individual player info panels as if captured(Get WHAT to connect to those UI elements I've got set up). It'd be simple enough even for me if this was a singleplayer, but since it's not I'm also refactoring a lot on the way as well. Thanks to both of the answers given so far I'm looking into Photon UtilityScripts(To a novice to anything simply directing where to look helps a ton, so thanks again), but since I'm not quite there yet I'll update my progress.
0
Attach a method to every GameObject or use a manager script I'm new to Unity but not new to development so I'm wondering what the standard way of doing this in with Unity. In the scene from the start is an empty GameObject that has a script that contains all of the items in the game. Once the game starts, chest prefabs are going to be spawned in the game and upon interaction they will reveal some random loot from the items script. Is it better practice to have a script on all of the chests that accesses the items script or should I create another empty GameObject as a sort of a chest manager that accesses the item script and keeps track of all of the chests in the game and what all of their loot is.
0
Multi Screen Rendering in Unity My experience with Unity in not that in depth. But I am wondering if it possible in unity to split what is being rendered across multiple screens. It's hard to explain, so here is an image So while the middle screen is fine to render, I want to spread the image all around the player. That is both to the side and, the bottom and top of the player. Is such a thing possible? Has anyone ever done something similar?
0
NavMesh.SamplePosition() fails after rebaking NavMesh? So today I was refurbishing a scene when this happened. After baking a new Navmesh the SamplePosition() returned only infinity. I tried a lot of things out but eventually went back to an older version of my project. Sooner or later I will have to bake a new Navmesh though, so I'd really like to know what happened there. Here is the part of the code that appears to cause trouble Vector3 randomDirection Random.insideUnitSphere roamRadius NavMeshHit hit NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1) direction hit.position And of course this, since it tries to look into infinity I suppose transform.LookAt(transform.position direction, Vector3.up) Again, this code works fine. Only after baking a Navmesh this fails horribly.
0
I need to replace the sprite at runtime Unity 2d I need a help, I have some code in Unity that should replace the player's sprite at runtime. But this code does not make it correctly, it does't make the change. Could you help me? Thanks using UnityEngine using System.Collections public class PlayerBehavior MonoBehaviour public enum Skins normal, verde private Skins skinAtual private Rigidbody2D player public float height private Transform posicao public float jumpForce 10f private AudioSource audio public DeathMenu deathMenu private float initialX public float goBackSpeed 10f Object BGMusics private SpriteRenderer sprite public SpriteRenderer sprites public Sprite skinVerde, skinNormal void Start () skinAtual Skins.normal skinAtual Skins.verde sprite GetComponent lt SpriteRenderer gt () player GetComponent lt Rigidbody2D gt () BGMusics Resources.LoadAll ("Music BG") initialX transform.position.x skinVerde Resources.Load lt Sprite gt ("Sprites BOYrECORTADOvERDE") skinVerde Resources.Load lt Sprite gt ("Sprites PersonagemFatiado verde") skinNormal Resources.Load lt Sprite gt ("Sprites PersonagemFatiado") private void UpdateSkin(Sprite novaSprite) foreach (var item in sprites) item.sprite novaSprite void Update () switch (skinAtual) case Skins.normal UpdateSkin (skinNormal) break case Skins.verde UpdateSkin (skinVerde) break default break if (Input.GetKeyDown (KeyCode.Escape)) Pause.INSTANCE.Pausing () if (Pause.isPaused) return if (Application.isEditor) inputComputer () else if(Application.isMobilePlatform) inputMobile () FixePosition () void FixePosition() if (transform.position.x lt initialX) return var newPX Mathf.Lerp (transform.position.x, initialX, Time.deltaTime goBackSpeed) transform.position new Vector3 (newPX, transform.position.y) private void inputMobile() if(Input.GetMouseButtonDown(0)) playerJump () private void inputComputer() if(Input.GetKeyDown(KeyCode.Space)) playerJump () private void playerJump() if (player.transform.position.y lt 8.93000f ) player.AddForce (new Vector2 (0, height jumpForce), ForceMode2D.Impulse) MusicManager.INSTANCE.JumpSound () void PlayRandom() int i Random.Range(0, BGMusics.Length) index sortido AudioClip m (AudioClip) BGMusics i uma referencia ao audioclip sortido GetComponent lt AudioSource gt ().PlayOneShot(m) tocamos esse audioclip void Reset() GetComponent lt AudioSource gt ().playOnAwake false aqui tira o play on awake do audio source CONFIGURANDO OS TRIGGERS E SUAS ACOES void OnTriggerEnter2D(Collider2D col) if(col.gameObject.CompareTag("Heart")) Score.INSTANCE.AddPoints () col.gameObject.SetActive (false) Handheld.Vibrate () TOCAR PlayRandom () else if (col.gameObject.tag "Doctor") MusicManager.INSTANCE.DeathSong () player.gameObject.SetActive (false) Handheld.Vibrate () ToggleEndMenu() void ToggleEndMenu() deathMenu.ToggleEndMenu (Score.INSTANCE.GetScore ()) Send to DeathMenu the Score value
0
How do I parent an object to a bone in the blender hierarchy? So, I'm trying to make a simple RPG game using Blender and Unity. I would like to have an empty object to be used as a weapon holding position parented to my right hand bone so that I can switch weapons in and out and they'll be able to animate along with my character by being the child of the empty position. The problem I am having is that I can't get the empty position to be a child of the specific right hand bone, only the armature. Is there a way to make this work? Also, if this isn't a good procedure to accomplish what I am trying to do, please enlighten me with the proper way, I'm kind of a noob, thanks.
0
How to Use Text in Unity3d How Can i Create Text in Unity3D? I Use "3D Text" But Its Always on Top Of Everything! Can You Suggest Anything? I creating a 2D Game So its not Necessarily a 3D Text.. Edit Because I Building a 2D Game My Scene is Full of Planes in Front of Camera And I want My Text to be Over One of the Planes and when plane is moving My Text appears behind it. But When I Use "3D Text" Its Always In Front of Everything. Sorry for My Bad English...
0
How do i draw a ray in unity So i am trying to scrap together something for vr in which the locomotion is about the player holding the direction where he wants to go to(basically planning what he is going to do)while holding down the button a ray is beeing drawn and when the player lets go the character moves until he reaches the end of the ray i tried looking up something but couldnt find anything regarding something like this
0
How do I use playerprefs to make ui slider keep the sound settings? I have not use playerprefs before, I want to know how to keep the change of the audio when the player change it throughout the game.
0
Best Way To Make Responsive UI Buttons in Unity I've been stuck on this for quite some time. I'm trying to make a platformer game for android so I need some touch buttons. I made some buttons in Photoshop but I can't figure out how to make them move the player right. I've tried implementing the IPointerDownHandler interface but once I get the player moving I can't stop it, even if I call a function in OnPointerUp to set the players velocity to a new vector3 where all values are zero. I've also tried attaching event triggers to the buttons I made, but it's the opposite the player only moves for one frame and then I have to press the button again. I don't want to import any assets from the asset store and I don't want to use gui system. I want to learn how to do it myself. Thanks in advance. Here is the script in which I call functions from my PlayerController. using UnityEngine using UnityEngine.UI using UnityEngine.EventSystems using System.Collections public class LeftButton MonoBehaviour, IPointerDownHandler, IPointerUpHandler public Image leftButton private PlayerController player private void Start() leftButton GetComponent lt Image gt () player FindObjectOfType lt PlayerController gt () public virtual void OnPointerDown(PointerEventData ped) Debug.Log("LeftButton Pressed!!") player.moveLeft ( 2) public virtual void OnPointerUp(PointerEventData ped) player.stopMoving () Debug.Log ("Button Lifted!!") Here is my PlayerController script. using UnityEngine using System.Collections public class PlayerController MonoBehaviour private Rigidbody2D myrb Use this for initialization void Start () myrb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () public void moveLeft(float moveSpeed) myrb.velocity new Vector3 (moveSpeed, myrb.velocity.y, 0f) public void moveRight(float moveSpeed) myrb.velocity new Vector3 (moveSpeed, myrb.velocity.y, 0f) public void stopMoving() myrb.velocity new Vector3 (0f, 0f, 0f)
0
Smoothly resize minimap camera rect width and height I have an orthographic camera that is working as a mini map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag void Awake() rectTransform transform.GetComponent lt RectTransform gt () public void OnPointerDown(PointerEventData data) if (!resizePanelFeatureActive) return rectTransform.SetAsLastSibling() RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition) public void OnDrag(PointerEventData data) if (!resizePanelFeatureActive) return if (rectTransform null) return Vector2 sizeDelta rectTransform.sizeDelta RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition) Vector2 resizeValue currentPointerPosition previousPointerPosition sizeDelta new Vector2(resizeValue.x, resizeValue.y) sizeDelta new Vector2( Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x), Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y) ) rectTransform.sizeDelta sizeDelta previousPointerPosition currentPointerPosition
0
How can "Box Collider is trigger" apply to the Player, not the enemies (make them collide, not pass through)? So, in my game, the Powerup (capsule) has a RigidBody and a Box Collider. I ve set the Box Collider to is trigger . When the player hits the powerup, it disappears just as it s supposed to. Is it possible to let the enemies collide with the powerup (bump into it) instead of just passing through it? From the Enemy script void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") Update is called once per frame void Update() if (player ! null amp amp gameManager.isGameActive) enemyRb.AddForce((player.transform.position transform.position).normalized speed) if (transform.position.y lt 4) Destroy(gameObject) gameManager.UpdateScore(pointValue) From the PlayerController script private void OnTriggerEnter(Collider other) if (other.CompareTag("Powerup")) hasPowerup true Destroy(other.gameObject)
0
Voxel Lighting in Unity3D I'm working on a Voxel project in Unity3D for fun and learning. I've been reading up on how this is done and have implemented a simple Voxel map in my project. My question is about the lighting. I've read several articles on how Minecraft implemented lighting. It doesn't seem too complicated but I'm wondering if it's necessary in Unity (and also I'm unsure how I would actually implement that in Unity) So far I'm just using Point Lights on blocks that should emit light. Is Unity's Point Light efficient enough on a Voxel map if there are many light sources? So far on my scene it works OK with several lights on it. Adding many lights slows down the game as expected but since my computer is not a gaming beast I don't know if it's because Unity's Point Light is not optimized for this type of map or if it's just due to my low end computer. (To give you a point of comparison, I run Minecraft with a lot of lag but Eldritch with absolutely no lag, if you're familiar with both those games) I would like some thoughts from more experienced users on this subject. If you had to develop a Voxel game in Unity, that may include 100 torches and 100 cubes of glowing lava, would you just use the Point Lights? If the answer is no, is playing with the RGB values of the block textures the way to go?
0
Getting grid coordinates of cells bordering a square region I have a board that is 4x4 ( the blue cells) with the origin (0 , 0) being in the bottom left for example, how can I get the coords which are adjacent to the board (the red cells) to store them in an array?
0
Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop? using System.Collections using System.Collections.Generic using UnityEngine public class Spin MonoBehaviour public Vector3 targetRotation public float duration public bool spinInUpdate false Start is called before the first frame update void Start() if (spinInUpdate false) StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration)) Update is called once per frame void Update() if (spinInUpdate true) transform.Rotate(new Vector3(0, 1, 0)) IEnumerator LerpFunction(Quaternion endValue, float duration) float time 0 Quaternion startValue transform.rotation while (time lt duration) transform.rotation Quaternion.Lerp(startValue, endValue, time duration) time Time.deltaTime yield return null transform.rotation endValue slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only The small cube when rotating either in update or in the Coroutine should not be slant. but it's slant in the Coroutine. And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ? About controlling the speed in the Update I just added a global float variable and in the Update transform.Rotate(new Vector3(0, Time.deltaTime rotationSpeed, 0)) and it's working for the speed.
0
Unity hangs when saving prefab asset For game saving purposes, I'm keeping track of references to ScriptableObjects through a lookup table, so that I can serialize deserialize using the SO's position in that table. I have a lot of individual SOs that I want to be able to serialize, so I wrote an editor script to populate that table automatically. The table exists in a MonoBehaviour on a prefab. Originally, I wasn't saving the prefab, because in the inspector it looked like the changes were successfully applying. However, those were showing in memory changes when you open the asset, the changes don't exist. The problem is, when I added the line to save the asset (PrefabUtility.SavePrefabAsset) Unity started hanging at the end of every import while showing that it was importing SO Lookup Table. I feel like I'm missing something obvious here, but Google hasn't been any help. What's wrong with my code? Here's the editor script. Every time assets finish loading, it adds any ScriptableObjects that aren't in the lookup table and exist in one of the specified directories, and removes any that were deleted from or moved out of those directories. public class SOLookupTableAutoPopulator AssetPostprocessor const string SO LOOKUP TABLE PATH quot Assets Prefabs SO Lookup Table.prefab quot every ScriptableObject in these directories is automatically added to the lookup table prefab static readonly string DIRECTORIES TO TRACK new string quot Assets ScriptableObjects ExampleDirectory1 quot , quot Assets ScriptableObjects ExampleDirectory2 quot static void OnPostprocessAllAssets (string importedAssets, string deletedAssets, string movedAssets, string movedFromAssetPaths) var lutPrefab AssetDatabase.LoadAssetAtPath(SO LOOKUP TABLE PATH, typeof(GameObject)) as GameObject var soLookupTable lutPrefab.GetComponent lt SOLookupTable gt () remove first in case asset moved between two tracked directories foreach (var path in pathsInTrackedDirectories(deletedAssets.Concat(movedFromAssetPaths))) soLookupTable.LookUpTable.RemoveAll(o gt o.Path path) var toAdd pathsInTrackedDirectories(importedAssets.Concat(movedAssets)) .Where(p gt AssetDatabase.GetMainAssetTypeAtPath(p).IsSubclassOf(typeof(ScriptableObject))) foreach (var path in toAdd) if (!soLookupTable.LookUpTable.Any(o gt o.Path path)) soLookupTable.LookUpTable.Add(new ScriptableObjectPathTuple(path)) PrefabUtility.SavePrefabAsset(lutPrefab) static IEnumerable lt string gt pathsInTrackedDirectories (IEnumerable lt string gt pathList) return pathList.Where(p gt DIRECTORIES TO TRACK.Any(d gt p.StartsWith(d))) The lookup table looks like this public class SOLookupTable MonoBehaviour public List lt ScriptableObjectPathTuple gt LookUpTable public int GetID (ScriptableObject so) return LookUpTable.FindIndex(o gt o.Asset so) public ScriptableObject GetSO (int id) return LookUpTable id .Asset And here's the class that the lookup table contains. I track the path in addition to the asset itself for the deletion phase of OnPostprocessAllAssets you can't retrieve an asset from a path that points to a deleted asset. Serializable public class ScriptableObjectPathTuple public ScriptableObject Asset public string Path public ScriptableObjectPathTuple (string path) Path path Asset AssetDatabase.LoadAssetAtPath(path, typeof(ScriptableObject)) as ScriptableObject
0
Animate a 3D boss with some parts that become independant I would like to create a boss but first, I want the player to fight the head. Then the head flies to the body and becomes attached to it. Later, the boss will throw an arm to the player and the arm will chase the player, becoming independent with its own AI. Do I have to render 3 models separatly? (The head one arm the body) If I do this, how am I supposed to animate the complete body when everything is attached together? Do I have to render the 3 models (The head one arm the body) 1 model without the arm (Head body) 1 model with everything attached? If so, how do I handle animations with these 5 models?
0
How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out?
0
My Raycast2D doesn't go where I want and it doesn't return a GameObject I want my Objects to teleport when they hit a wall. For that, I want to shoot a Ray backwards and teleport it to where the ray hits the wall, but whatever I try, it always teleports to the centre of the scene and the ray hit doesn't return a GameObject. This version I tried runs on OnTriggerEnter2D RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up, 300) Debug.DrawLine(transform.position, hit.point) transform.position hit.point I tried some other variations too. If you have any idea, please let me know.
0
How to make variables restart when the game restarts? My game is all in one scene so when my player dies and the user clicks restart the game (when it shows the game over screen) the script below doesn't restart with it so the enemies are still going fast when the user is replaying the game. How do I make it restart when the game restarts? if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 This is used in my score script. The Movement.movespeed is a reference to my movement script attach to my enemies making them go faster when the player collects 10 points.
0
Unity assembly files missing from "Temp bin Debug" I'm trying to use VS Code on a Mac with Unity and C . When I try to open a Unity project in VS Code, it can't load Assembly.dll files from few locations which are defined by default in .csproj files "Temp bin Debug ". When I check the Temp bin Debug paths, while Unity is running, they are empty they doe not contain the assembly files, where I assume they should. The files are in "Library ScriptAssemblies". Moving them is not an option, because I would have to do that manually every time I change sth. in any script file. Changing the path in the .csproj files is also not a good idea, because those files get rewritten every time you open a project in Unity. This issue causes lot of problems in the editor WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' INFORMATION OmniSharp MSBuild Update project Assembly CSharp Editor firstpass WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' INFORMATION OmniSharp MSBuild Update project Assembly CSharp Editor WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp Editor firstpass.dll' WARNING OmniSharp MSBuild Unable to resolve assembly ' ... Temp bin Debug Assembly CSharp firstpass.dll' All type references coming from my custom scripts and the UnityEngine namespace are missing, and highlighted as errors However, intellisense seems to be working fine for UnityEngine types I tried to reinstall MonoDevelop it a few times, including a brew and downloadable package. MonoDevelop seems to be installed properly mono version Mono JIT compiler version 4.6.2 (mono 4.6.0 branch ac9e222 Wed Dec 14 17 02 09 EST 2016) Copyright (C) 2002 2014 Novell, Inc, Xamarin Inc and Contributors. www.mono project.com emsp emsp TLS normal emsp emsp SIGSEGV altstack emsp emsp Notification kqueue emsp emsp Architecture x86 emsp emsp Disabled none emsp emsp Misc softdebug emsp emsp LLVM yes(3.6.0svn mono master 8b1520c) emsp emsp GC sgen .NET works as well dotnet version 1.0.0 preview2 1 003177 How do I fix this?