_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Mesh vs LineRenderer Performance I've created a script, which is drawing a line along a bezier curve, so that I can animate whatever I want with lines, mostly for UI purposes. For the moment I'm using a line renderer, which works, but the performance is not that great in my opinion. So I was wondering if there are actually some better methods to draw lines, like simply creating a mesh along the path I've got.
|
0 |
How to detect collision in C script not attached to any game object I have public variables which I populate through the inspector. One script is attached to a single object and the other script has a gameObject array property. Please see below public class GamePlayScript MonoBehaviour public BallScript ballScript public BrickGroupsScript brickGroupsScript Use this for initialization void Start () Update is called once per frame void Update () BrickGroupsScript contains an array of bricks which has a isBroken bool property. Also the above code is attached to an empty game object. How can I detect when the ball game object is in contact collided with a brick with isBroken true?
|
0 |
Would it be possible to randomize LOD distance in unity like in BOTW grass I was studying the BOTW grass shader and noticed how the grass appears uniform at a distance but complex up close. From watching gameplay it appears the LOD is randomized to make the transition between the two types of grass smooth. I can't find any way to do something like this in unity and am wondering if anybody has advice, or can guess as to how they did it. Thanks!
|
0 |
How do I set the Foot IK property of an animator state by code? I would like to set Foot IK to enabled via code, but I can't find how. Which type is quot Foot IK quot a part of?
|
0 |
Initialize an object in property drawer based on an int variable in Unity I have created following classes for my game in unity System.Serializable public class abstract BaseA System.Serializable public class DeriveABaseA BaseA System.Serializable public class DeriveBBaseA BaseA System.Serializable public class abstract BaseB public int Type 0 public int AType public BaseA A System.Serializable public class DerivedABaseB BaseB DerivedABaseB() Type 1 System.Serializable public class DerivedBBaseB BaseB public DerivedBBaseB() Type 2 System.Serializable public class ClassC public int BType public BaseB B public class ClassD MonoBehaviour public List lt ClassC gt C now, I'm trying to add my custom editor for them. this is the first time I'm using editor scripting and I have few question regarding how to add custom editor scripts for my classes What is the correct way of adding new element to variable C How can I call PropertyDrawer for ClassC when I'm drawing C elements? How to initialize variable B of class ClassC based on the user entered value for variable BType in class ClassC? How can I call DerivedABaseBPropertyDrawer or DerivedBBaseBPropertyDrawer based on type of variable B in class ClassC? How to initialize variable A of class ClassB based on the user entered value for variable AType in class ClassB? This is code code that I was able to get it to work except for 2nd and last question CustomEditor(typeof(ClassD)) public class ClassDEditor Editor ClassD m target public override void OnInspectorGUI() m target (ClassD)target if (GUILayout.Button("Add")) Is this the correct way of adding value to this list? m target.C.Add(new ClassC()) foreach(var c in m target.C) How propertydrawer can be called for each element of C? CustomPropertyDrawer(typeof(ClassC)) public ClassCPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) Is the following code valid (it's working) and is there a cleaner simpler way of doing this? object obj fieldInfo.GetValue(property.serializedObject.targetObject) var index System.Convert.ToInt32(new string(property.propertyPath.Where(c gt char.IsDigit(c)).ToArray())) ClassC objC ((List lt ClassC gt )obj) index if(objC.BType 1 amp amp typeof(objC.B) ! typeof(DerivedABaseB)) objC.B new DerivedABaseB() else objC.B new DerivedBBaseB() CustomPropertyDrawer(typeof(ClassB)) public ClassBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) How to get access to B instance object var type property.FindPropertyRelative("Type").intValue var a type property.FindPropertyRelative("AType").intValue var drawer null if(type 1) drawer new DerivedABaseBPropertyDrawer() else drawer new DerivedBBaseBPropertyDrawer() if(a type 1) Set A new DeriveABaseA() else Set A new DeriveBBaseA() CustomPropertyDrawer(typeof(DerivedABaseB)) public DerivedABaseBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) CustomPropertyDrawer(typeof(DerivedBBaseB)) public DerivedBBaseBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
|
0 |
Unity Convert Camera Gyroscope Attitude to World Space Canvas rotation Suppose you have a worldspace canvas parallel to a camera that is rotated by the gyroscope. How do you convert from the camera's gyroscope attitude to get the world space canvas rotation?
|
0 |
Associating game object with some class Disclaimer Somewhat long winded question amp new to developing In my game I have a class called Item which defines what an item is. It contains several fields like the name of the item, the sprite of the item, the item's ID number, etc. I also have little physical objects on the ground that "represent" items, but they aren't really tied to the Item class in the way I want. I'll get back to this point. So, when an enemy dies in my game, SpawnItem(Item item) is called. Depending on a randomly generated number, SpawnItem(ItemData.sword) might be called or SpawnItem(ItemData.axe) and so forth. SpawnItem itself just instantiates a generic prefab (that little physical object on the ground), modifies some state like bool itemDropped and int numItemsDropped, makes some calculations to determine where to drop the item, and displays that item's name in a UI label above the item. I'm currently in the process of making an inventory system, and I've realized something. Those physical objects on the ground that are supposed to be items don't really know that they're items (in the sense defined by the class). A sword doesn't know it's a sword, and an axe doesn't know it's an axe (the game object sword doesn't know that it's a sword Item defined by the class) So when I pick up an item, I can probably do some code gymnastics to get the appropriate sprite to appear in the inventory, but that doesn't seem like a smart solution. So, my question is how do I get my sword game object (just a sphere on the ground representing a dropped item) to be linked to the sword Item? How do I get the sphere to know that it represents a sword with the ID number "1", the name "Sword", a weight of "1.5" etc. so that I don't have to do awkward code gymnastics? After all, when I'm adding an item to my inventory, I don't really think of it as JUST drawing that item's sprite in the first non empty slot of the inventory. I would think it's much better to get each game object to know what Item it represents than to just try and get that sprite to show up in the inventory. I might be overlooking something basic, but understand that I'm pretty new to Unity. Anyway, thanks for the time and help!
|
0 |
Is it possible to make isometric game of 200 200 tiles per map in Unity? We made an isometric game in AndEngine. Now we want to convert this game into Unity. I am searching for tiles map support plugin in Unity. I come across a plugin called Map and nav http forum.unity3d.com threads 138355 Tile Based Map amp Nav . but the problem is it only support 50 50 tiles per map. My map is 200 200 tiles. I want to know is there any plugin or way to acheive 200 200 tiles per map in Unity ? Thanks
|
0 |
How to show a canvas text when i click an UI button on Android I am trying to show a text when i click on a ui button but i don't know how to implement this. On PC platform I have a collider per object and when the player stay and click the E button, a canvas text appear on screen, but i don't know how to do this on Android. I want something like Resident Evil old style action button, opening doors and getting object description. How could i do this? The Script public class readingNote MonoBehaviour public AudioSource audio public AudioClip collectSound public bool playerNextToKey false bool hasCollided false public GameObject pic public GameObject text public GameObject notePad private Collider other void Start () pic.SetActive(false) text.SetActive (false) public Button yourButton void Start() pic.SetActive(false) text.SetActive (false) Button btn yourButton.GetComponent lt Button gt () btn.onClick.AddListener(TaskOnClick) void TaskOnClick() can't text.SetActive(true) because when i get out the scene, text is showing up (I use the same button to open doors and get text description). void OnTriggerStay ( Collider other) if(other.gameObject.tag "Player") if(Input.GetKeyDown(KeyCode.E)) text.SetActive (true) pic.SetActive(true) AudioSource.PlayClipAtPoint(collectSound, transform.position) void OnTriggerExit ( Collider other ) if (other.gameObject.tag "Player") enter false print("close") playerNextToKey false hasCollided false pic.SetActive(false) text.SetActive (false)
|
0 |
How can I remove Unity Hub in Ubuntu? I installed Unity Hub 1.4.0 and it works well. For now I want to update the version of Unity. I need to install hub 2.0.0. But when I download the 2.0.0 hub and intsall it always link to 1.4.0 and I want the version Unity 2019.1.10f1. I can't find some uninstall files. How can I remove Hub 1.4.0?
|
0 |
Create 3D line instead of a thin line in Unity in runtime with mouse drag I know how to use line renderer to drag and drop to create line in runtime, but the line appears to be thin when looking from the end of the line, I want to create a real line that has a thickness(think of it as a tube or pipe shape), no mater where the look direction is, they should has a thinkness. How would you achieve this effect, I've got two ideas, 1.Create a rectangle shape, then extrude this shape to create mesh during runtime, but the manipulation of mesh during runtime is too complicated for me. or 2.Create prefabs, and spawn new prefabs and connect them along the cursor routing to make them looked as they were a continous line. Would you suggest me of some new ideas or existing package to achieve this effect, or is the first option is the way to go? What I want to do is to make a shader editor like appearence in 3D space, what I need to create is the edges, and the edges should look 3D instead of 2D line.
|
0 |
How to make gameObjects in Unity move in predefined patterns easily I am trying to make a bullet hell game. I want my 2D enemies to move in predefined, curving patterns. How should I do this? The difficulty I have is being able to quickly produce enemy movements that are (A) predefined, not random (B) curved (C) easy to make, with little coding (D) visually able to see what is going on, maybe in the inspector? Perhaps a 3rd party tool may be warranted?
|
0 |
Why my calculated value is far different from actual value? I using CharacterController and not using a Rigidbody so I writing a script for downward velocity which is velocity 9.81 (time) and I declare my initial velocity as 12. Supposing from this calculation, the max height it can reach from the equation is roughly 6.7891 unit on y axis. By using the formulae distance travel initial velocity (time) 0.5g (time) 2,differentiate this w.r.t time, getting time u g 12 9.81 1.223, then max distance travel 12 (1.223) 0.5 ( 9.81) (1.223) 2 7.339 but from the coordinate below, can clearly seen the max distance travel before falling down is 13.2803unit 0.5499unit 13.8302unit? This is far exceed calculated value, wonder what went wrong? Initial coordinate of y on ground 0.5499 approximate final coordinate of y 13.2803 using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if(Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime)
|
0 |
Unity 5.5 Modify image of a button from an array of images via script Logic Help Right now i have this Is a placeholder for what i want to do. This blue circles are images in different buttons, i have a blue image circle for every letter. I have to display the correct letter image to create a word. For example word "DOG" and the word is created by the "D" "O" "G" images. That is the logic i cannot get my head around. How can I, via script, select which image to show depending on the word given? IDEAS I have an array of (INDEX, "letter") in my GameController.CS. Maybe i can add a number to the different images name. Separeate the word in characters. Look the position of this character in the Letters and that number turn it into a string and find the image with that number in the name. I really need help to figure this out. Thanks in advance for any help.
|
0 |
How can I detect continuous touches pressed with Unity 4.6's UI elements? I've recently switched to Unity 4.6. My previous workflow when creating continuous input controls (the kind where you measure continuous touch input on a single button) was to create a GUITexture and then perform hit testing on that texture as long as a finger was touching the screen. With the new GUI there seems to be no way to measure this type of input, as GUITextures objects can no longer be created and the new UI types don't support hit testing. I'm talking about a button that's supposed to act like a car accelerator where, for example, a simple OnClick() doesn't work because I need to measure if the button is being pressed continuously rather than it working as an on off toggle. How can I implement this?
|
0 |
How do make a box collider align with a line renderer continuously? I am having the issue of aligning my BoxCollider2D with my linerenderer. I am trying to have a laser shoot using Physics2D.Linecast(startingPoint.transform.position, maxEndPoint.transform.position) This works fine and the line is always shooting in the right direction and angle when I rotate the object. But, when I am drawing a box collider, the box doesn't align at the correct position. Firstly, the boxcollider is attached as a child component of the line renderer. I am using this code to get the size of the collider, which seems to work fine. float lineLength Vector3.Distance(lazer.GetPosition(1), lazer.GetPosition(0)) This code is for aligning the collider with the line renderer. I know I am supposed to get the midpoint, because that's how you control the location of the box collider, but I need to know the math to always make it align. lazerCollider.offset new Vector3(0, ourHitPos.y startingPoint.transform.position.y, 0) 2 lazerCollider.size new Vector3(lazerWidth, lineLength, 0) I know right now I am only using the Y coordinate... I just need to know the math to make this work.
|
0 |
Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?
|
0 |
Why is there a white border around my app icon? EDIT This is because Unity did not support Android's adaptive icons. As of Unity 2018, it is supported natively. For Unity 2018 , see this question. For Unity 2017 , see Jimmy's answer. I am developing an Android app in Unity. I have two versions of the app on my phone, both with identical icons. The white border is only on the newer version of the app. I am using a Google Pixel. Why is this there, and how do I get rid of it? Is this tied to my phone or my app? If it is tied to my phone, why is it on one icon, but not the other (they are same icon)? I don't want other users to have this pointless border around the app, as my icon already has a border.
|
0 |
How to flatten the collider for a tilemap? I am relatively new to game development, and am working on a simple 2D platformer. I have created a tilemap and painted some tiles for the character to walk on.. but he is getting stuck. Yes, I know this is a common question and I did find some answers (including this one Player gets stuck on edges between TilemapCollider2D tiles), but none seem relevant for me. The thing is my tiles are not flat.. they have pointy edges due to grass.. see the image below As you can see, the edge is not flat. I have overcome the problem of getting stuck by changing the quot Edge Radius quot to what you see in the above screenshot and that works, but the character now looks like he is floating slightly above the ground. Is there any way I can just tell Unity to ignore the jagged grass and make the collider flat and move the edge of it down a bit? That way it would fix the issue and also have the added bonus of looking like some of the grass is behind him and some in front..
|
0 |
Unity Input System Rebinding composite parts I have controls for movement defined as composite Binding through Vector 2D. I have shown in settings any single binding which is not composite. I understood that I must get a composite index for binding, which is correct, I got the right binding like up, down, ... But whenever I click on button for change something on Move, whole game freezes. And I can't do anything... Is there something I'm missing, when rebending part of composite? Here is my code and screen, how the control settings looks. public void Start() Button.onClick.AddListener(() gt Key.Text quot Listening quot operation Action.PerformInteractiveRebinding() .WithTargetBinding(BindingIndex) .Start() operation.OnApplyBinding((op, path) gt Action.ApplyBindingOverride(BindingIndex, path) Key.Text Action.bindings BindingIndex .ToDisplayString() operation.Dispose() ) )
|
0 |
Shader Directional Lights Depth Is there a way to retrieve the deph from directional lights ? I can access the ShadowMapTexture but this is not the depth. I found how to access the shadow map of, I think, every light type by using the defines such as SHADOW ATTENUATION(a) or directly the ShadowMapTexture, everything is located in the built in shaders. But I am wondering how could I access the depth of those lighting type. I found a way to access it for the spot light this way ShadowCoord.z which gives the depth scaled with ShadowCoord.w, which could be considered to the far plane, but am I right ? How could I do the same for the other light types such as directional or point lights ? For the moment I am stuck with directional lights, any clues ? Because if I try to access the depth for a directional light by using ShadowCoord.z it seems that it's more related to the depth view and not the light. Here I am, totally stuck with this directional lights.
|
0 |
How to make a script work when clicked only on the given prefab? I am very new to unity but not to C . I am working in Unity 2D I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable. So how do I make a script work only when clicked on that specific prefab
|
0 |
How to make Unity Layout switch while in Play mode I'm looking for a way to auto switch the Unity layout when I go to play mode. I want to Unity Editor layout automatically changes to my preset layout when I click on Play button and When I stop the game, It goes back to the default layout.
|
0 |
Unity3D profiler isn't helping. How to debug increased memory? Using Instruments or Xcode, my iOS game uses around 115 MB memory when the menu scene is loaded. After doing battles and other things within the game and reloading the menu, the memory usage is up to 170 MB. The real problem is that Unity's profiler doesn't tell me anything there are a few MB of extra system libraries and a few MB of extra Texture2D assets, but there's no explanation for the big increase. Adding more Resources.UnloadUnusedAssets() and GC.Collect() doesn't help. How can I investigate this? (Note it reaches a steady state. The memory doesn't continue to rise after a certain point.)
|
0 |
How to detect when the current animation is finished in code in Unity's Animator? I have a model with an animation controller. I set the states and parameters for transitions between them. Now I need to make the model play its animations in the order I want. I can use GetComponent. lt Animator gt ().SetBool("someparameter",true) to uncheck currently checked parameter and check another parameter after current animation finished. Please help me to find a way to make a condition "when the current animation finished". The examples I'm finding are related to animation component (not animator), or they are too complicated for me, while I need a simple way I can understand and use quickly. Thank you so much in advance!
|
0 |
Unity Colliders How do I detect nearby objects without my detection ranges detecting each other How can I get both colliders' types in a trigger overlap message like OnTriggerExit2D(Collider2D other)? Example objects A and B both have a BoxCollider2D and CircleCollider2D components. Then, object A enters one of the trigger colliders of object B. I can get object B's collider type with the is operator. How can I get A's collider type? The reason I want this is that I want only collisions where object A's CircleCollider2D touches object B's BoxCollider2D. void OnTriggerExit2D(Collider2D other) if (other is BoxCollider2D) Do Code Here is a table of what I want I want only to register trigger overlaps from CircleCollider2D to BoxCollider2D. With the is operator, I can safely remove all collisions to CircleCollider2D but collisions between two BoxCollider2D stay, which I do not want. Row to Column BoxCollider2D CircleCollider2D BoxCollider2D No No CircleCollider2D Yes No Edit The real questions was to detect nearby objects without the detection range dectecting each other.
|
0 |
Applying Animation to specific parts of a humanoid model I have imported a humanoid character from AutoDesk Character Generator into Unity. Once you specify that you want the character for Unity, a humanoid skeleton in integrated, in order to use MecAnim. I also have a plug in that applies the user's motion data to this character and animates it. Because the plug in is free and open source, I am trying to apply the motion data to different MecAnim bones, to see if I can do so. By the way, by "motion data" I am referring to 2 arrays one that contains positions and one that contains orientations of a number of joints and bones. So, I can access these Vector3 and Quaternion data... Is it enough to just apply, for example, the left foot's orientations to the right foot, or do I need to also do it with positions, in order to inter change the animations motions movements of these 2 limbs? This is the method I have written so far public void swapLimbsPosRot(Vector3 positionsArray, Quaternion rotationsArray) Vector3 tempPos positionsArray 16 positionsArray 16 positionsArray 20 positionsArray 20 tempPos Quaternion tempRot rotationsArray 16 rotationsArray 16 rotationsArray 20 rotationsArray 20 tempRot But it doesn't work, because when I apply it to my array of transforms before updating, severe jitters show there is a fighting going on between MecAnim and my motion capture device' incoming motion data, but for now I am just wondering If you wanted to swap the animations movements motions of 2 similar MecAnim parts, what would you do? What would you swap? How would you go about it? p.s. Of course, first I tried swapping the mecanim bones (right amp left feet) but that turned out silly, as the "actual" feet of my MecAnim character had been swapped! Some code, showing how the swapping and updating are done now, hoping someone could please help me find the cause of the jitters. void Update() Vector3 latestPositions Quaternion latestOrientations if (mvnActors.getLatestPose(out latestPositions, out latestOrientations)) If this variable is set to true, then do the swapping. if (swapLimbs) swapLimbsPosRot(latestOrientations) Update both the pose and the model, using the delayed data. updateMvnActor(currentPose, latestPositions, latestOrientations) updateModel(currentPose, targetModel) Swap the rotations of different mimicking limbs e.g. LeftHand 16 amp RightHand 20 public void swapLimbsPosRot(Quaternion rotationsArray) float tempRotY rotationsArray 16 .y rotationsArray 16 .y rotationsArray 20 .y rotationsArray 20 .y tempRotY float tempRotZ rotationsArray 16 .z rotationsArray 16 .z rotationsArray 20 .z rotationsArray 20 .z tempRotZ The motion data that comes in is always the latest positions and orientations from the device, so Update modify them and then apply them to the character to animate it. So, for example, in my Update, I get the latest pose (i.e. the latest positions and orientations) and then I swap the orientations of left and right hands, but the jitters are severe...
|
0 |
What is the physical interpretation of Input.GetAxis("Horizontal")? Actually I want to edit my previous question titled What is the geometrical interpretation of Input.GetAxis("Mouse X") and add a related question "What is the physical interpretation of Input.GetAxis("Horizontal")?" to it. However, I was asked to create a new question about it. The longer I press the key, the greater the value returned by Input.GetAxis("Horizontal"). If I don't press, it returns 0. The value seems to be a function of time interval the key is pressed. What is the empirical relationship between the relevant quantities?
|
0 |
Removing walls of a tilemap at runtime in unity I've been trying to implement some light procedural generation into my game, nothing fancy. Just spawning rooms down in different areas in order to add some replayability. I watched a few videos and the prevailing wisdom seems to be creating room prefabs and placing them at points in the world which I have done. Its at this point I want to differ my implementation than those online, I would like to at runtime remove tiles at the North, South, East and west parts of the walls like so. My main problem is trying to figure out where these points are in the tile map, I have tried creating empty game objects and adding them as children to the Tilemap and taking their positions and then using Tilemap.SetTile(child.transform.position,null) to remove the tiles, however the tile that ends up being set is always wrong and offset by a certain amount, I have tried to use Tilemap.bounds and Tilemap.localbounds to try calculate the width and height of the Tilemap in order to get the midpoint between 0 width and 0 height but the bounds of the Tilemap is actually way bigger than the space my tiles actually cover in the world, so that's also untenable. Using Tilemap.WorldToCell or Tilemap.LocalToCell also has not worked. If this is impossible, or just way more complicated than its worth, are there other ways for me to draw rooms at runtime that dont involve me creating a big 2D of gameobjects with sprites and colliders because that'll just tank my performance. Heres the Code I'm using to loop through all the children of my Grid and check if they contain the correct tag (North South East West) and then using that position to swap the tile void clearTiles(string dir) List lt Transform gt tiles FindComponentInChildWithTag(this.gameObject,dir) foreach(Transform t in tiles) map.SetTile(new Vector3Int((int)t.position.x,(int)t.position.y,0),tile) public static List lt Transform gt FindComponentInChildWithTag(GameObject parent, string tag) Transform t parent.transform List lt Transform gt children new List lt Transform gt () foreach(Transform tr in t) if(tr.tag tag) Debug.Log(tr.name quot quot tr.localPosition quot quot tr.position) children.Add(tr) Debug.Log( quot Children size quot children.Count) return children
|
0 |
How can I generate spheres equal between the waypoints? public void duplicateObject(UnityEngine.GameObject original, int howmany) howmany for (int i 0 i lt waypoints.Count 1 i ) for (int j 1 j lt howmany j ) Vector3 position waypoints i .transform.position j (waypoints i 1 .transform.position waypoints i .transform.position) howmany UnityEngine.GameObject go Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity) go.transform.localScale lightsScale objects.Add(go) For example howmany value is 21. If I have two waypoints it's fine it will create 21 spheres between the two waypoints. But if I have 3 waypoints it's creating 42 spheres but it should create 21 since howmany is still 21. And it also position the spheres between waypoint 1 and 2 and then from waypoint 2 to 3. But I want that it will create 7 spheres between waypoints 1 and 2 and 7 spheres between waypoints 2 and 3 and last 7 spheres between waypoints 3 and 1.
|
0 |
Unity 3d auto move player forward script Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get. I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls) Thank you!
|
0 |
Collider does not call callback functions I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field. I check different tutorials and documentation and cannot find a way to do this in code. My code looks like objectToPlace (GameObject)AssetDatabase.LoadAssetAtPath("Assets Game 3D Models Buildings " objectName ".fbx", typeof(GameObject)) objectToPlace.SetActive(true) objectToPlace.transform.localScale new Vector3(1, 1, 1) objectToPlace Instantiate(objectToPlace) objectToPlace.transform.Rotate(Vector3.right 90) BoxCollider collider (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider)) collider.isTrigger true In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6? I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.
|
0 |
Get MouseUp event outside of Sceneview scene window? So I have an editor script that uses a dragging operation which works quite nicely. Except, if you release the button while OUTSIDE the Scene Window, the event doesn't register. How do I detect mouseup outside of the scene window? private static void OnScene(SceneView sceneview) Event e Event.current if (e.type EventType.MouseDrag) do some drag stuff e.Use() if (e.type EventType.MouseUp amp amp e.button 1) is the Right Mouse button released? I suspect somehow it's due to my Event e being inside the OnScene making the mouse actions only existing in the context of the Scene Window perhaps? I have no idea, very new to Editor scripting...
|
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 to stop counting point when player dies (Destroy) In my game, I'd like to stop counting points when the player's y is 4. When the pink and red balls fall off the Plane the player gets points. But it seems a bit strange to be able to collect points after the player dies. This is the code for the player if (transform.position.y lt 4) Destroy(gameObject) gameManager.GameOver() And in the GameManager.cs I have this public bool isGameActive public void UpdateScore(int scoreToAdd) score scoreToAdd scoreText.text "POENG " score public void GameOver() isGameActive false restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) And this is the code for adding points when the enemies fall over the edge if (transform.position.y lt 4) Destroy(gameObject) gameManager.UpdateScore(pointValue) How can I make the game stop counting points when the player dies?
|
0 |
Overuse of Canvas in Unity3D I'm currently trying a new approach on a Card Game in Unity. To capsuling my Card Prefab i have a root GameObject with the Canvas Component. I'm highly count on the Canvas behavior which should render things after the main scene rendering. Elements on a canvas are rendered AFTER scene rendering, either from an attached camera or using overlay mode. Before i further proceed, i want to know if there are any disadvantage of this, when my Game Logic approximately generate 100 200 of this GameObjects? Should the Canvas Component not be overused in Unity?
|
0 |
Unity Animator not properly following animation transitions I have an Animator that has 3 different states. Walking, Climbing, and End of Climb. The diagram is shown below I have 2 bools, isClimbing and isWalking. When isClimbing is set to false it transitions to End of Climb. Then when I set isWalking to true, it transitions to Walking. However, when I do this, for some reason the animator starts back at Climbing then moves to End of Climb then moves to Walking. It seems everytime I change a parameter, it completely restarts the state machine back to the default Climbing state and then moves forward. I do not have code, and have been triggering this through the UI. What am I doing wrong?
|
0 |
Why does OnControllerColliderHit not work while Physics.CheckSphere() does? Using the following code below, when my character hits a crate and goes over it, it ends up floating in the air, while jumping is no issue. That successfully lands on the ground. using UnityEngine public class Testing MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if (Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime) Here's an image showing the floating player And why does the code below (using Physics.CheckSphere()) have no issue? Feels like the above code is better (if working correctly), as it doesn't need to waste resource on checking the condition of Grounded (like in checkstate1()) every frame. using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller public float Speed 12f public float Gravity 9.81f Vector3 velocity public LayerMask groundmask float hp 90 bool Grounded true Update is called once per frame void checkstate1() Grounded Physics.CheckSphere(this.transform.position, 0.85f,groundmask) if (Grounded true) hp velocity.magnitude Debug.Log(hp) velocity.y 0 public void Checkstatus() if(Grounded false) velocity.y Gravity Time.deltaTime void Update() checkstate1() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp Grounded true) velocity.y 12 Grounded false Checkstatus() Controller.Move( velocity Time.deltaTime)
|
0 |
How do I allocate to a C dictionary having a string key and an integer 2D array or transform for value? I'm working in C on a Unity 2D game that spawns a shape that has only one correct landing place. There are 7 basic shapes but the component 4 squares of each shape are unique, with each bearing, say, a unique number. There are many more than 7 unique shapes because any component square is unique to the shape set. So the shapes have squares bearing a unique number (1,2,3,4 on a square 5,6,7,8 on another square 9,10,11,12 in a line (I shape), 13,14,15,16 in another line (I shape), etc. each of these shapes must be moved (by dragging, dropping or rotating) to its particular place in the grid. I need to swiftly (1) indicate whether a shape has landed correctly and, if not, (2) move the misplaced (and possibly mis rotated) shape to its proper location so that remaining falling pieces are not blocked from attaining their correct placements. For (1), I'm using a dictionary with a string for the key that identifies the square component of the shape and an integer 2D array for the grid location values. Here is the declaration Dictionary lt string, int , gt dictOfProperLocations new Dictionary lt string, int , gt () Visual Studio is OK with that. But I am unable so far to allocate key value pairs to the dictionary. I've tried the following and variants to indicate that a straight shape (an I shape) bearing the numbers 1 4 belongs at the origin at its left end and stretches straight to the right dictOfProperLocations.Add("1", 0,0 ) dictOfProperLocations.Add("2", 1,0 ) dictOfProperLocations.Add("3", 2,0 ) dictOfProperLocations.Add("4", 3,0 ) But Visual Studio objects to that. I find many examples for C dictionaries with string keys and 1D array values, but no examples for this case with 2D array values. Or might this be better handled with a 2D Transform , for the values representing the proper grid locations? Thank you.
|
0 |
Why is Unity MouseLook very shaky and jittery? I'm working on a first person shooter game. My problem is that my Mouselook script is shaky and jittery when I looking around. Here is my code Transform MyTransform const string vert input "Mouse Y" const string horz input "Mouse X" public float mouseSensitivity 100.0f public float clampAngle 80.0f void Update() the time Time.deltaTime ROTX ROTY.y (Input.GetAxis(horz input) mouseSensitivity current speed offset the time) ROTX ROTY.x (Input.GetAxis(vert input) mouseSensitivity current speed offset vertical the time) ROTX ROTY.x Mathf.Clamp(ROTX ROTY.x, clampAngle, clampAngle) MyTransform.rotation Quaternion.AngleAxis(ROTX ROTY.y, Vector3.up) x rot transform.localRotation Quaternion.AngleAxis(ROTX ROTY.x, Vector3.left) And this is my input settings for Mouse X and Mouse Y For more explanation I put my camera inside one of my controller children and if I put it out of controller the issue is still there. I tried Lerp, Slerp, smoothdamp , euler but does not make any difference. I tried this script for Android and I used a touch instead of a mouse and the result was same. I tried it on FixedUpdate and the result was same. Is there any way to fix this problem? Here is a video about my problem.
|
0 |
Sprite Rendering Cost Calculation First of all asking before asking this question I have already read following post for the clearance of my mind. Sprite Renderer Texture 2D I want to change my background texture as per device aspect ratio detection. For this purpose I have following code var newSprite Sprite function Start () GetComponent(SpriteRenderer).sprite newSprite Or another way to load sprite is Sprite myFruit Resources.Load("fruits 1", typeof(Sprite)) as Sprite Using above code I can able to load new sprite as per my requirement. But I want to reduce following disadvantage from this. At present basically I set background sprite of 960 x 640 for iPhone 4 and its get loaded. After that I change my background sprite to 2048 x 1536 as I detect the device with iPad Retina display. So another texture get loaded. I want this process to happen single time so how to manage sprite texture in correct way. Also thanks for your attention towards this question.
|
0 |
Get world position of random point inside bounds I am trying to get a random world position inside my targets collider, so that I can fire an arrow at it. I have tried a bunch of different solution but can't seem to get it right, for example (this code is on my target) Inside Awake colliders GetComponentsInChildren lt Collider gt () I want this to work on a unit with a single capsule collider and a building with 8 different box colliders public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) float minX gameObject.transform.position.x gameObject.transform.localScale.x bounds.size.x 0.5f float minZ gameObject.transform.position.z gameObject.transform.localScale.z bounds.size.z 0.5f return new Vector3(Random.Range (minX, minX), gameObject.transform.position.y, Random.Range (minZ, minZ)) In the scenario I'm having issues with right now, the trageet simply has a single capsule collider. This return a point quite far away from my target, but I cant find the issue. EDIT Here is another one I tried without success public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) var target new Vector3( UnityEngine.Random.Range(b.min.x, b.max.x), UnityEngine.Random.Range(b.min.y, b.max.y), UnityEngine.Random.Range(b.min.z, b.max.z) ) return b.ClosestPoint(target)
|
0 |
UnityIAP Subscription Purchase Basically I want to setup UnityIAP for implementation of weekly or monthly subscription for apple store game. I completely read following article given by Unity Integrating Unity IAP In Your Game After this I become aware with actual implementation but i have following questions arise how we can get information about subscription already purchased by this user? how we track time for auto renewable subscription purchase? Please give me some information about this.
|
0 |
How can I access the normal map value in Unity? I'm simulating laser scanners in Unity with Raycasts, and I've got some quot bumpy quot items I'd like to scan. I had tried generating the actual geometry for these objects, but there are tons of these objects and the polygon count exploded. What I would like to do is something like described here to get the color from a raycast intersection Renderer renderer raycastHit.collider.GetComponent lt MeshRenderer gt () Texture2D texture2D renderer.material.mainTexture as Texture2D Vector2 pCoord raycastHit.textureCoord pCoord.x texture2D.width pCoord.y texture2D.height Vector2 tiling renderer.material.mainTextureScale Color color texture2D.GetPixel(Mathf.FloorToInt(pCoord.x tiling.x) , Mathf.FloorToInt(pCoord.y tiling.y)) But, instead of getting the color, I'd like to access the normal. I used grayscale bump maps to simulate height differences, but the raycasting doesn't take the normal map into account and I can't figure out how to access normal map values. Ideally there'd be some texture2D.GetNormal() I could use in place of the texture2D.GetPixel() given in the snippet above, but I can't seem to find anything anywhere on getting at the material normals. I'm using Unity 2019.4, with the Universal Render Pipeline at the moment.
|
0 |
Initial setting of camera and ppu to match playing table My goal is to implement another board game as close as possible as I would play it on a table to not much think about how to arrange elements. The used space on table is in the dimensions of around 1x2m and most of my assets are scans of game cards with a touch of Photoshop (for personal use only). My question is regarding the camera, pixel on import of asset and converting to units. There are no physics in the game involved and it is 2D. For now it will be tailored to my own mobile but I would like to know if one way is preferred if I wanted to later change resolution or is just better best practice. From my understanding it would result both in the same outcomes but there might be some hidden trouble or side effects. Should I (convert for myself to get a feel for dimensions) take 1 unit as 10cm gt scene of 10x20 units would represent my table or rather have a 1x2 unit scene (since most take one unit as one meter) Assuming my scanned card has something like 2000x1000 pixel (and is 10x5cm big on a real table), does it make more sense to have it imported as 2000 20000 under pixel per unit or downscale the image first before importing it with a lesser value? I don't really care currently about build asset size.
|
0 |
Unity 2D Tap to shoot at mouse position on android device Hello everyone i am really stuck at the moment and would appreciate any help if possible. I have my game where i move the player up and down with 2 buttons on the bottom left of screenshot. I also have a button over the entire screen for tap to shoot and this moves the weapon to my finger position where i have tapped and it shoots towards that position using mouse.position. Now the problem is when i am on my android device and i am moving up and down but when i also tap to shoot the gun it moves towards my up and down buttons and this is not what i want. i want to be able to move with my finger and also shoot towards the second finger. Any ideas would be greatly appreciated. Here is my Tap to shoot button code! public void ShootButton() timer 0 Face true if finger presses Shootbutton then activate this Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position subtracting the position of the player from the mouse position. difference.Normalize() normalizing the vector meaning all the sum of the vector will be to 1. float rotZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg find the angle in degree. WeaponTrans.transform.rotation Quaternion.Euler(0f, 0f, rotZ rotationOffset) if (reloading false) if (fireRate 0) Shoot() else if (Time.time gt timeToFire) timeToFire Time.time 1 fireRate Shoot()
|
0 |
How to dynamically create an UI text Object in Unity 5? I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically in my real case application, I will do that in a loop of not pre defined number of iterations. A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include using UnityEngine.UI in my C code, and also that I could declare a UI Text like Text guitext. However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown using UnityEngine using System.Collections using UnityEngine.UI public class MyClass MonoBehaviour Text guitext Use this for initialization void Start () guitext.text "testing" Update is called once per frame void Update () Worse than that, it seems that while game is played, no new object appears in the object hierarchy list. Could you please point me out in the right direction here? Thanks.
|
0 |
How to get time since frame start in Unity for loading purposes I am building a big world (1000 game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making yield return null . The main issue is when to fire yield return null . If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low end devices. My idea is simple to detect how much milliseconds have passed since the start of the frame and fire yield return null just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS). However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.
|
0 |
Reused Avatar moves mesh I have a humanoid avatar and it's animation controller. I also have two different human meshes, they're quite similar. When I use the generic avatar and it's controller in the animator the meshes shot out into the sky and perform their animation correctly. The animations run normal they just move in weird directions and don't stay in their original locations. How to fix it so the mesh doesn't move far away and retain original position?
|
0 |
Find grandchildren with specific tag I have an empty object that contains multiple children each containing their own child objects. I want to get a list of all the objects containing a specific tag but i don't know the depth of each child object. The following solution only returns the children that have the tag. foreach (Transform child in city) if (child.CompareTag("Zone")) buildings.Add(child)
|
0 |
How to implement a mechanic of entering a town I am planning a game played on a 2 D map, where some spots are "towns". When the player walks into a town, he enters a high resolution map of this town when he exits the town, he returns to the low resolution map of the world (as in e.g. Ultima 4). My question is how to implement this enter exit mechanism in Unity? I thought of two approaches The world map and each of the town maps is a different scene. Entering exiting a town is implemented by loading the appropriate scene using the scene manager. There is a single scene, but the maps are geographically separted. For example, the world map is in coordinates 1...256, town A map is in coordinates 301...364, town B map is in 401...464, etc. Entering exiting a town is implemented by moving the player and the camera to the appropriate map. Is there a better approach? What approach is commonly used to implement this mechanism?
|
0 |
How to save Unity assests to another drive? My C volume has almost no space left. Therefore I want to transfer all my assets to the volume E . And save my new assets automatically on the E volume. I have searched very long in unity for save options of unity assets but nowhere found a setting option for this.
|
0 |
How can i change the cube scale only on Y and only to up? This is the script I am working with using System.Collections using System.Collections.Generic using UnityEngine public class Raise MonoBehaviour public GameObject Ladder float mfX float mfY float mfZ Use this for initialization void Start() mfX Ladder.transform.position.x Ladder.transform.localScale.x 2.0f mfY Ladder.transform.position.y Ladder.transform.localScale.y 2.0f mfZ Ladder.transform.position.z Ladder.transform.localScale.z 2.0f Update is called once per frame void Update() Vector3 v3Scale Ladder.transform.localScale Ladder.transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y 0.1f, v3Scale.z 0.1f) Ladder.transform.position new Vector3( mfX Ladder.transform.localScale.x 2.0f 0, mfY Ladder.transform.localScale.y 2.0f, mfZ Ladder.transform.localScale.z 2.0f) The way it is now it's making the whole cube bigger and bigger. But I want to make the cube grow only UP on Y. To keep the cube capacity extent But to make the scale change only up. If I'm doing Vector3 v3Scale Ladder.transform.localScale Ladder.transform.localScale new Vector3(0, v3Scale.y 0.1f, 0) Ladder.transform.position new Vector3(0, mfY Ladder.transform.localScale.y 2.0f, 0) I will see it go up in scene if I select the cube in the hierarchy but if not I will not see the cube at all. Can't figure out how to make is grow up only up side.
|
0 |
Unity 2D Input.gyro eulerAngles X value strange behaviour I am working on a project where I want to create an 'scrolling' effect using gyroscope on mobile devices. The basic idea is that I have an Image object in my Scene and I want to be able to show different part of it using gyroscope like for example you see the wall of a room and rotation your phone you see different parts of the room, but in 2D. For now I managed to move my Image using Input.gyro.attitude.eulerAngles.x from gyroscope like this protected void Update() var x transform.localPosition.x var gyroX Input.gyro.attitude.eulerAngles.x x gyroX Speed BackgroundImage.transform.localPosition new Vector3(x, transform.localPosition.y, transform.localPosition.z) The problem which I am seeing is that when Input.gyro.attitude.eulerAngles.x reaches 86.0 it starts decreasing and even if you are rotating your phone to right it changes it's direction. Checked the documentation, examples over internet, but didn't find anything about that. If you have any idea what can cause that issue and how can I fix it, or any other suggestions how can I achieve the thing which I want to create, pleae share your knowledge. Thanks in advance! Edit The only rotation axis which I am interested in is X, because the app will be in portrait mode and I want to be able to move the image only horizontal (by X). So the phone's rotation has to be similar to while taking an panoramic photo on your mobile as shown on the first picture
|
0 |
(Unity) Spawning AI cars weighted to ahead of camera? I'm working on a little project where I drive around a small city with a top down but slightly angled camera view (like GTA Chinatown Wars). Cars are instantiated from spawners that aren't in camera view, then destroy if they drive too far from the player. To spawn a new car, I loop through all my spawner gameobjects and if they are within a certain distance to the player (and not in view of the camera), then they get added to a 'spawner' list, of which I pick a random. The loop is something like this float dist Vector3.Distance(player.transform.position, spawner.transform.position) Vector3 screenPos Camera.main.WorldToViewportPoint(spawner.transform.position) bool inView screenPos.z gt 0 amp amp screenPos.x gt 0 amp amp screenPos.x lt 1 amp amp screenPos.y gt 0 amp amp screenPos.y lt 1 if (!inView amp amp dist lt 15) list.Add(spawner) This works, but I find that when I'm driving around barely any traffic spawns on roads ahead of me, maybe because the camera angle is removing a chunk of the possibility area. Is there anyway to 'weight' it so spawners in the direction the camera (or beyond) have more chance of being picked, rather than ones behind me? In games like GTA Chinatown Wars you will be driving through rows of traffic, and I'm trying to get more density.
|
0 |
OnTriggerExit() called when game object with collider component gets re parented I have an object Hand, with a rigid body attached to it. In every Update() call, the user's hand controller rotation and position are tracked. In my scene, there is an object Pin, with a mesh collider attached to it. In OnTriggerEnter() (inside the Hand class), Pin becomes re parented to Hand. (Pin's original parent is something else.) My scene also contains other objects with colliders. However, these other objects do not get re parented only Pin does. Once this re parenting takes place, OnTriggerExit() (in the Hand class) is called immediately. This is surprising to me I had expected OnTriggerStay() (in the Hand class) to be invoked instead, since Hand is still in contact with Pin. Is such behaviour by design? Is there an elegant way of working around such behaviour? UPDATE In response to this comment Does the pin object have a parent before it becomes a part of the hand? Yes. As mentioned in my post, Pin's original parent is something else. Or is it placed inside another collider? And does the pin leave any of these collider areas when the parenting takes place? As mentioned in my post, Pin itself has a mesh collider component attached to it. Perhaps I am not understanding the question correctly... You can prevent the hand's script from getting this OnTriggerExit by adding a seperate rigidbody to the pin. I added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() inside the Hand class is still called immediately after Pin gets re parented. MORE INFORMATION Pin's original parent (before it gets re parented to Hand) does not itself have a collider component. When OnTriggerExit(Collider collider) gets called immediately after the re parenting takes place, the collider argument passed to the method is the Pin itself.
|
0 |
How can I create a stretchy, breakable pizza cheese material? I want to create realistic pizza and allow user interact with it. What I want What I created I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle". How can I make the cheese stretch and break when the user moves a piece?
|
0 |
How can I make a gameObject jump quick at first then start slowing down after a while? How can I make a gameObject jump quick at first then start slowing down after a while? It definitely has something to do with deltaTime.
|
0 |
what is use of ScriptableSingleton in Unity? in unity 2020.x Unity just has introduced scriptable Singleton. a class that derives from Generic Class Called ScriptableSingleton its like singleton but you only can have single instance of it and seems to be good for ScriptableObjects that need to be Forced to be Single. but there are some differences. they can be project Specific or Shared. they can get any format and unlike usual scriptableObjects they have no visualization in the inspector. the question is how should i use them and they are appropriate for which approaches? this is the link to the reference https docs.unity3d.com 2020.1 Documentation ScriptReference ScriptableSingleton 1.html
|
0 |
Unity3d wheelcollider falling through terrain I have created simple project with 3D car and terrain. I have added 4 Wheel Colliders on model wheels. But when I run project wheels falling through terrain. Before run After run I am sure that at start wheel colliders above the terrain and not intersect it. Configuration is In what problem is? I have tried a lot of different things but I can't find a solution.
|
0 |
How to put a reference to my player (already instanced) into a prefab that will be instantiated later I'm making an enemy in my game. He stands at the side of road with a rocket launcher and fires when you get close. It nearly all works fine, except I just need a reference to the players position so that I can make his rocket explode when it reaches the same height on the map as the player car. The enemy is a prefab which is NOT instanced at build time, there a several spawn points all with n chance of spawning a guy there using the prefab. The player IS instanced at build time. And here is my problem.. Although I have put a "public GameObject player" into my variables in the script on the prefab, it doesnt let me drag the already instanced player into it. I've read about a bit, and I see that Unity will not allow this (or at least thats what I gathered!) So after much searching I came up with player GameObject.FindGameObjectWithTag("Player") But i havent even tested yet because the source where i got that advice in the very next comment the guy says I shouldnt do this because it takes too much system resources up. EDIT I have tested it with that line, it does work. But is there a better way But he doesnt say the way that it should be done! And the thread is about 6 years old. So I thought I'd write here again and ask you fine folks for more help. I hope I explained the problem clearly enough, I think i got the terminology right. Basically, the RocketerEnemy prefab is going to be instantiated in runtime, but the PlayerCar is already instantiated by my dragging it into the heirarchy at the beginning of the project. This is stopping me from dragging the PlayerCar object into the box in the Inspector (for the Enemy prefab) . All I really need is the PlayerCar.transform.position.Y value for each frame. THANKS IN ADVANCE !
|
0 |
How to make the snake bodyParts follow same places and directions as the player on a curved surface? I try to make a game like the classic snake game but on a round ground (Earth). On a plane, the script works well, but when i moved it on a sphere, the bodyparts (prefabs), are not working good as you can see in the picture ( they are going right left, but they do not sit on the spehre and i tried already to use sphere collider, box collider, rigidbody) and i dont know really how to make it so that they will follow 100 correctly the player. Thanks for help! . Here i put the script for the Player and bodyparts using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class PlayerMovementScript MonoBehaviour protected Joystick joystick public float speed SerializeField private float turnFactor SerializeField private Transform planet public List lt Transform gt bodyParts new List lt Transform gt () public float minDistance 0.25f public int beginSize public float rotationSpeed 50 public float timeFromLastRetry public GameObject bodyprefabs public Text currentScore public Text scoreText public GameObject deadScreen private float dis private Transform curBodyPart private Transform PrevBodyPart public bool isAlive void Start() joystick FindObjectOfType lt Joystick gt () speed 3f StartLevel() public void StartLevel() timeFromLastRetry Time.deltaTime deadScreen.SetActive(false) for (int i bodyParts.Count 1 i gt beginSize i ) Destroy(bodyParts i .gameObject) bodyParts.Remove(bodyParts i ) bodyParts 0 .position new Vector3(0, 0.5f, 0) for (int i 0 i lt beginSize 1 i ) AddBodyPart() bodyParts 0 .position new Vector3(0, 0.5f, 0) bodyParts 0 .rotation Quaternion.identity currentScore.gameObject.SetActive(true) currentScore.text quot Score 0 quot isAlive true void Update() if (isAlive) Move() if (Input.GetKey(KeyCode.Q)) AddBodyPart() RotateAroundPlanet() var rb GetComponent lt Rigidbody gt () rb.velocity new Vector3(joystick.Horizontal 100f, rb.velocity.y, joystick.Vertical 100f) public void Move() float curspeed speed if (Input.GetKey(KeyCode.W)) curspeed 2 bodyParts 0 .Translate(bodyParts 0 .forward curspeed Time.smoothDeltaTime, Space.World) if (Input.GetAxis( quot Horizontal quot ) ! 0) bodyParts 0 .Rotate(Vector3.up rotationSpeed Time.deltaTime Input.GetAxis( quot Horizontal quot )) for (int i 1 i lt bodyParts.Count i ) curBodyPart bodyParts i PrevBodyPart bodyParts i 1 dis Vector3.Distance(PrevBodyPart.position, curBodyPart.position) Vector3 newpos PrevBodyPart.position newpos.y bodyParts 0 .position.y float T Time.deltaTime dis minDistance curspeed if (T gt 0.5f) T 0.5f curBodyPart.position Vector3.Slerp(curBodyPart.position, newpos, T) curBodyPart.rotation Quaternion.Slerp(curBodyPart.rotation, PrevBodyPart.rotation, T) public void AddBodyPart() Transform newpart (Instantiate(bodyprefabs, bodyParts bodyParts.Count 1 .position, bodyParts bodyParts.Count 1 .rotation) as GameObject).transform newpart.SetParent(transform) bodyParts.Add(newpart) currentScore.text quot Score quot (bodyParts.Count beginSize).ToString() public void Die() isAlive false scoreText.text quot Your score was quot (bodyParts.Count beginSize).ToString() currentScore.gameObject.SetActive(false) deadScreen.SetActive(true)
|
0 |
Can t find component Unity so, I want to add a Cloth component. I click on a gameobjects, press Add Component in the Inspector search Cloth And nothing comes up. From my searches in google, nobody had such a problem ever, nor is there any answers. How can I fix it? Or reload reimport the physics components? Unity version 2019 Thanks in advance!
|
0 |
Help deciding data structure for spatial partitioning, using only value types in c I simply want to implement some sort of grid where I can sort units in an RTS into cells, and then for each unit check to avoid other units and attack other units, in 2d. My map grid is currently 10 000 x 10 000 cells, with 20 thousand units. To be specific, my grid is sparse but the units move together in very dense groups of about 300 each (like an ancient army type of formation). So cells will either be extremely dense, or completely empty, no in between really. My issue in deciding is that I am using Unity job's system and burst compiler. If you do not know, jobs is a multithreading system, and burst is an LLVM based compiler outputting very fast assembly. The limitations of these systems is you can only use value types. So no classes. I have looked at using a MultiHashmap, but from what I read this can be very slow because I need to run a hash function for every unit. Then when I want to iterate al units in a cell, this is much slower than iterating an array. Especially, because I will also be checking the 8 neighbour cells for each unit as well. That's a lot of hashing being done. Finally, I have to clear the map every frame. The advantage here is Unity provides a container NativeMultiHashMap which is thread safe, so I can build and query it in parallel. I have looked into quad trees. But quad tree does not seem suited to multithreading, especially without using references. So if I did this, it would most likely be single threaded. My question is, are my above statements correct in thought? Is there a faster way to organize my data? If I go with a hashmap, how can I query it most efficiently?
|
0 |
Help creating combat for collection type game sorry for my odd terminology, I am rather new to all this I'm creating a collection pokemon type game. as of right now I have created a separate GameObject prefab for every monster character in the game. Each gameobject contains a script with enumerated values for it's stats. When combat begins It calls a random monster from a pool of gameobjets. The problem is at this point I'm not sure how to have it create a new instance of the enemy in a way where it retains the values in it's public floats from the prefab or have it's level be adjusted as it enters. And I don't know how I can derive it's stats and properties for scripts outside the function that spawned it. as the function that creates the new duplicate won't remember the new creature after the function resolves. so In short, How can I reference the enumerated integers of a newly duplicated gameobject I was asked to include some more information on what I've coded public List lt baseMonsters gt allMonsters new List lt baseMonsters gt () public void EnterBattle(Rarity rarity) this code swaps camera view to the battlefield from the overworld map playerCamera.SetActive(false) battleCamera.SetActive(true) call function to determine which monster appears baseMonsters battleMonster GetRandomMonsterFromList(GetMonsterRarity(rarity)) returns which monster was chosen Debug.Log (battleMonster.name) prevents the player from moving after combat begins player.GetComponent lt PLayermove gt ().isAllowedtoMove false Creates the defending monster GameObject dMon Instantiate (emptyMon, defencePodium.transform.position, Quaternion.identity) Ensures scale from original is preserved dMon.transform.localScale battleMonster.transform.localScale Vector3 MonLocalPos new Vector3 (0, 1, 0) dMon.transform.parent defencePodium dMon.transform.localPosition MonLocalPos Adds the stat components of the original prefab baseMonsters tempMon dMon.AddComponent lt baseMonsters gt () as baseMonsters tempMon battleMonster dMon.GetComponent lt SpriteRenderer gt ().sprite battleMonster.image bm.ChangeMenu (BattleMenu.Selection) the issue that I see with the code is that it's transforming an already existing object into what the prefab monster is, not copying it. what method can I use to copy the prefab in a way I can easily reference in the same function to change it's level? Update ok so changing everything over to instantiating a GameObject is what I want. now there is the other part from the code before public List lt baseMonsters gt GetMonsterRarity(Rarity rarity) List lt baseMonsters gt returnMonster new List lt baseMonsters gt () foreach (baseMonsters Monster in allMonsters) if (Monster.rarity rarity) returnMonster.Add (Monster) return returnMonster public baseMonsters GetRandomMonsterFromList(List lt baseMonsters gt monList) baseMonsters mon new baseMonsters () int monIndex Random.Range (0, monList.Count 1) mon monList monIndex return mon I was following a tutorial when I created this code, I am starting to understand more and more how spaghetti it is. sorry for all the Alike Terms, baseMonsters is a class that houses things like the rarity and stats of the monster. These functions are searching by and for that script. How can I convert these codes over to searching the class from a list, to a Gameobject from a list, and still be able to read baseMonsters of each respective GameObject and it's rarity int? as of right now, one workaround I can think of is to create a seperate list for each rarity. that way I can skip needing to read the rarities in the baseMonsters script entirely. But I will still need to know how I can call that class script for other things like determining level of the monster and what it's attacks will be?
|
0 |
How to place an object at the mouse position? How can I place a object to position where I clicked in just x,y axis not in z, I am trying to achieve it with Vector3 mousepos Camera.main.ScreenToWorldPoint(Input.mousePosition) object.transform.position new Vector3(mousepos,mousepos) but it does not seem to work, in fact the object doesn't even move.
|
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 |
Normal mapping for Android and iOS I'm making a mobile game for Android and iOS on Unity. At the moment I am researching and designing the technical aspects of the game. Since it is not plausible to use highly detailed models for mobile platforms, should normal mapped models be used instead? Thus I have couple of questions about normal mapping. Are normal mapped models much more costly to make, in other words, do they take a lot longer to create? And are they much more expensive to render? At least there are no additional draw calls, but of course the shader is more complex.
|
0 |
Why is an empty Unity Iphone Build over 700 Megs? Is this Normal? So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size. 770 Megabytes For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs Why is an empty Iphone project this large?
|
0 |
Unity 3D Rotate towards object with random offsets Title is a little confusing, but let me explain I want to make the enemies look at the player, and shoot at him, with random precision, meaning that one time the enemy will shoot a little bit to the left of the player, next time a little bit to the right of him, and sometimes exactly at him. Currently I have this scene The turret rotates, and when the green direction spots the player, it shoots a bullet facing the player (the green arrow). Now I need where the rotation is passed for the Instantiate, to have some random precision, and I don't know how to do it. Here's what I have so far Vector3 pos new Vector3(firingPoint.transform.position.x, firingPoint.transform.position.y, firingPoint.transform.position.z) float playerX playerObject.transform.position.x float playerY playerObject.transform.position.y float playerZ playerObject.transform.position.z float randomX Random.Range(playerX 1f, playerX 1f) float randomY Random.Range(playerY 1f, playerY 1f) float randomZ Random.Range(playerZ 1f, playerZ 1f) Quaternion aimPrecision Quaternion.LookRotation(new Vector3(randomX, randomY , randomZ)) Instantiate(bulletPrefab, pos, aimPrecision) How can I do this? EDIT Right now, the enemy shoots like this but never towards me, or backwards
|
0 |
Large gap between the grabbed game object and controller When i grab a gameobject, there is a gap between them. I have tried changing the scale of the colliders, tool handle position from global to pivot but nothing worked for me. Should i reset the pivot points of model in 3D modeller and reimport it again or is there another way to solve this? I have attached few screenshot related to the problem
|
0 |
Conversion of a C library to DLL I'm developing an augmented reality application and I'm supposed to use the ALVAR library for AR marker detection. I use Unity as the game engine and unfortunately it doesn't support C . Is there any possible way to use the C library as a DLL?
|
0 |
Do I need to initialize a public List variable in Unity? I want to create a list of horses and print the name of the Horses that are stored in the list. Although I got the answer correct as I desired, there's one thing that is puzzling me when I declare a list variable. I declared it as public List lt string gt myFavouriteHorses and in an example I have seen it's declared like this public List lt string gt myFavouriteHorses new List lt string gt () Despite this difference, both of them worked. What's the difference between these two approaches? Does it matter which one I use? Here's the entire code which i tried using UnityEngine using System.Collections.Generic public class LearningScript MonoBehaviour public List lt string gt myFavouriteHorses new List lt string gt () void Start() myHorses () void Update() if (Input.GetKeyDown (KeyCode.Return)) Print () void myHorses() myFavouriteHorses.Add ("Grey Horse") myFavouriteHorses.Add ("Black Horse") myFavouriteHorses.Add ("Rudolph Horse") myFavouriteHorses.Add ("Biting Horse") void Print() Debug.Log ("This list has " myFavouriteHorses.Count " horses") Debug.Log ("The horse at index 1 is " myFavouriteHorses 1 ) Debug.Log ("The horse at index 2 is " myFavouriteHorses 2 ) Debug.Log ("The horse at index 3 is" myFavouriteHorses 3 ) Here's the output Why doesn't it make a difference whether or not I initialize the List with new before using it?
|
0 |
How to make changes to array of prefabs in editor to be visible in game window I attached the following script to an empty game object (EnemiesGO) in the editor. public class EnemiesScript System.Serializable public struct EnemyWithType public EnemyScript enemy public EnemyScript.Type enemyType public EnemyWithType enemyPrefabs public EnemyScript enemies void Start () enemies new EnemyScript enemyPrefabs.Length for (int i 0 i lt enemyPrefabs.Length i ) enemies i Instantiate lt EnemyScript gt (enemyPrefabs i .enemy) enemies i .enemyCategory enemyPrefabs i .enemyType When I was populating enemyPrefabs (through the editor) I didn't see the prefabs in the popup selection window so I dragged them directly from the Assets window Assets Resources Prefabs EnemyPrefabs. My question is two fold. If it is possible, how can I get the populated enemyPrefabs array to be displayed in the game window scene window before I run the game? In general, I would like to see changes effected from the editor in the game window before I run the game. How can I access the EnemyPrefabs folder from the popup selection window?
|
0 |
Unity, WaitUntil in a self made message box class I managed to make a simple message box prefab with a Text and a Button through Canvas, and then instantiate it through the constructor. public class MessageBox public MessageBox(string msg) GameObject obj (GameObject)MonoBehaviour.Instantiate(Resources.Load( "MsgBox")) obj.GetComponentInChildren lt Text gt ().text msg So when another script needed it, simply do MessageBox mb new MessageBox("This is a test message!") This all worked fine, but then I wish to change it to like normal MessageBox where the code was suspended, but not locked, until the user click the OK or Cancel button. I managed to do it by calling a coroutine in the calling script. void Start() StartCoroutine("Do") IEnumerator Do() MessageBox mb new MessageBox("This is also a test message!") yield return new WaitUntil(() gt GlobalVariables.MsgBoxClicked true) GlobalVariables is a separate class containing some static variables. Debug.Log("Done!") (You have to set the MsgBoxClicked to false when the prefab is created and set it to true when the button is clicked, of course.) But that means every time I needed to use the message box, I need to call a coroutine! And that's super inefficient no matter how you looked at it! So I tried to move the coroutine into the MessageBox class itself. But now here comes the problem! The MessageBox does NOT inherit from MonoBehaviour! And you can't call a coroutine without it! I had tried to make the MessageBox inherited from MonoBehaviour, but the Unity warned me This is not allowed every time I tried to new it! Even though the game ran smoothly. I even tried to new the MonoBehaviour itself and call its StartCouroutine, but of course, the same warning popped up! And this time the game won't even run! I also tried to use the old AutoResetEvent, but it locked the whole thing and crashed my game! So, could somebody be so kind and teach me how to get around it!? Much appreciated!
|
0 |
An invisible object that deletes anything behind it? I am using augmented reality to put a 3D object on top of a "camera detected" object. The 3D object can be though of as leaves that go above the real world object but also fall in front behind on the sides of it. The leaves are not uniform so they appear as arcs which let more of the "camera detected" object be seen in some parts and less in others. Because of this I want to only show the leaves that would normally be seen if there was a real 3D object (instead of the camera detected one) in that place. But since the camera detected one is just a background image part of the leaves on the side or behind are seen when the object is rotated. I was thinking it might be possible to use an "invisible" object that moves and rotates the same way as the "camera detected" one so it behaves as a placeholder for depth testing but is not actually rendered. Is this possible? May I have some pointers on how to achieve this? Thank you
|
0 |
Trouble referencing a bone transform in Unity. (Using MakeHuman armature configured in Avatar ok Anim mocaps working ok)) I've seen that the bones are Transforms. And i've tried copying many examples. The armature is the standard MakeHuman one and is unchanged. It imported to Unity fine and the mocap animations work perfectly. What I need to do is make the hand a parent of my gun . Here is what I have currently (I have tried many similar permutations) Transform handR public GameObject gunPrefab GameObject gun private void Start() rb GetComponent lt Rigidbody gt () playerAnims GetComponentInChildren lt PlayerAnimations gt () absoluteGround rb.transform.position.y distToGround GetComponent lt Collider gt ().bounds.extents.y handR transform.Find("hand r") Debug.Log("handR really is " handR) gun GameObject.Instantiate(gunPrefab) gun.transform.SetParent(handR) gun.transform.position handR.position gun.transform.rotation Quaternion.identity The end result of this The gun will spawn but isnt parented to anything. And if I try to set its position using handR.position then i get null exception. Pic above shows the image where I see its called "hand r" One more thing of note The bones shown in the image above , do NOT appear in the hierarchy. I have on occasion imported models with the bones included whose bone names all appear in the hierarchy could this be the reason Unity is finding "hand r"??? and if so whats the best way to fix that (Please done say remove the armature and make my own in Blender !! O ) PS I have since tried it with a new model, made in Blender with a Rigify rig. The code part "handR transform.Find("hand R") yes the rigify rig names it with capital "R". Still doesnt work, BUT THERE IS A WORKAROUND I FOUND... if I make the Transform handR public and drag it into the Inspector it all works fine! (And yes the Rigify skeleton also shows up in hierarchy!) (So if you are reading this and struggling too, DONT use the MakeHuman skeleton, use one from Blender Rigify.) But I'm still very confused why the "Find" command doesnt find the bone
|
0 |
In Cricket games, how is the ball synced with batsman's shot animation? How does the ball hit right at the center of the bat? How does this work? I've been trying to figure this out for quite some time now. In Cricket games, when the bowler bowls, and batsman takes a shot, how does the ball sync with batsman's shot animation? For example, let's say the batsman hits a straight drive, how does the ball hit the bat perfectly? Can anyone help me out with this? I'm also curious about how in football games, the player animations sync with the football. How does the player's foot correctly hit the ball? Thanks in advance.
|
0 |
Adding Google IAP License Key into Unity Games I have added Google Play Services and AdMob successfully into my app. But I want an in app purchase button that lets you remove the adverts. (I have the button already but not the billing). Google Developers Console tells me I need to input my app's specific license key into my app. The Android Manifest.xml to be specific. But it's not the clearest instructions. The Unity guide seems very lacking too, and mostly I can only find stuff about Unity IAP. The Unity guide I did find tells me it makes the Manifest automatically and only tells me that I can write my own complete Manifest and import it over the top of the auto made one. I don't really want to do that if possible as I have just finished adding all the other Google stuff via Unity into the Manifest.xml I'm sure this is a common feature that lots of devs use, so that makes me think there must be some way to do it via Unity.
|
0 |
Dynamic frame rate in Unity I'm developing a 3D visualization tool based on Unity, targeting WebGL. The user rarely interacts with the 3D scene and when he does it's only about adjusting the camera like rotating or zooming the view. I disabled vSync (QualitySettings.vSyncCount) and locked the frame rate to 30 (Application.targetFrameRate) to reduce the CPU usage at least a bit while still having an acceptable level of responsiveness when the user moves the camera around. With 30 fps I get a CPU usage of around 30 . Considering lower end hardware this seems still too high. In order to further decrease CPU usage, I introduced two 'modes' Interactive runs with 30 fps Idle runs with 10 fps I wrote some lines of code to switch between those modes depending on user interaction. So when an input is detected, the application uses more fps and after a certain amount of time without any interaction, the application uses less fps again. It works pretty well so far The app uses 30 in interactive mode and 8 to 10 of the CPU while in idle mode. Setting the idle frame rate to 1, CPU usage is reduced to 1.5 while in idle mode. This is really great. But as expected there's a problem. Basically I locked all the Update() methods to be called only once per second. When the user interacts with the camera, the event will be processed with an expected delay of something around one second. Now the question How can I detect user input immediately while having the application run with a low frame rate and also immediately apply a new frame rate (say 30) without any noticeable delay? Originally I wanted to have some sort of on demand rendering. I've read some posts about how people render to a texture to reduce rendering cost in less interactive scenes. But setting the frame rate dynamically seems like a cleaner solution in my opinion. I also tried to use the FixedUpdate() method to check for inputs and switch to interactive mode, but that didn't work either. Note Also worth mentioning, this approach produces errors in the browser, indicating that the application frame rate should be 0 (not in terms of Unity's target frame rate but as in 'let the browser handle the frame rate'). While this might be a different question it's still related to this topic. Maybe someone has an answer for that as well! Edit 1 As mentioned in the comments below, Unity provides the callbacks MonoBehaviour.OnApplicationPause and MonoBehaviour.OnApplicationFocus to detect whether the application is about to receive or lose focus. However, the problem is this My application nearly never loses focus. While this is a nice additional optimization it doesn't really help me too much. My problem is that the app is idle most of the time while also having focus. It's really just the user staring at the window most of the time. Just to make some more sense I'm targeting WebGL. Unity's sole purpose is to visualize some stuff while the user mainly interacts with some HTML controls. In the rare case he wants to interact with the 3D scene, I want to set the frame rate to say 30. The idea is quot I don't re render the scene too often as long as you don't interact quot . To emphasize In my most relevant use case the application never loses focus. This means, the only reliable indicator to determine when to switch between frame rate profiles is based on user input. Sorry if I wasn't too clear about that ) Edit 2 I posted this topic on the Unity Feedback Page. If you're interested, check it out and leave a vote. Maybe this request gets enough attention to get supported by the Unity developers.
|
0 |
Baked vs realtime global illumination in unity I use unity. So far I know that the baked GI is less GPU processing when the game is played so if possible, I need to use baked GI. Newbie question I'm using unity and just curious in the light setting, is there any situation or in what condition that we can turn on both realtime and baked GI at the same time? Or is it only practical to turn on one of them?
|
0 |
Share content FROM Facebook, not to it Regarding Unity 2018.x The Facebook SDK provides a way to get log in information from a user's FB account, and allows information or an image from an app to be shared TO Facebook. Is it possible to link access reference or in any other way make use of a specific image on Facebook within my Unity app? Ideally, I would like to be able to access the image upon target recognition and, even better, store the image for subsequent display within the app. Finally, even more ideally ideally, this would not be the FB profile picture. All suggestions and links welcome.
|
0 |
Fitting Gameobjects within camera view I am trying to fit a grid of gameobject into the orthographic view but I have a problem whenever I change the amount of grids to display it would overlap the view. What c n I do to fit a series of gameobjects, having always the same margin as the amount of grid changes? private void Start() for(int i 0 i lt wordSearch.Gridsize i ) for(int j 0 j lt wordSearch.Gridsize j ) cell Instantiate(gridCell, new Vector3(j 1 gridCell.transform.position.x cellSpacing, i 1 gridCell.transform.position.y cellSpacing, 0), Quaternion.identity) cell.name "cell Y " i.ToString() " cell X " j.ToString() GameObject textObject cell.transform.GetChild(0).gameObject textObject.GetComponent lt TextMeshPro gt ().text wordSearch.matrix i, j .ToString() textObject.name textObject.GetComponent lt TextMeshPro gt ().text CenterPoint() FitToScreen() private void CenterPoint() Vector3 offset new Vector3(0, 1, 10) cellGameobject GameObject.FindGameObjectsWithTag("cell") transformCell new Transform cellGameobject.Length for(int i 0 i lt cellGameobject.Length i ) transformCell i cellGameobject i .transform for(int a 0 a lt transformCell.Length a ) cellVectors transformCell a .position centercell cellVectors transformCell.Length GetComponent lt Camera gt ().transform.position centercell offset private void FitToScreen() Camera.main.orthographicSize Insert Comment
|
0 |
Shader change alpha depending on light I use Unity, and I need a shader a bit special. Unfortunatly my skills about shaders are very limited and I need this shader quickly. So I want a shader to display a unlit texture on a plane, and when a light affect the plane, instead of make the lighting on the plane, I want that the light change the alpha to make the "lighted" surface transparent. I think that it's not very hard for someone who know how to make shaders, so if you can help me to do this, it can be very useful for me! Edit Ok, maybe it's not very clear. I speak about a light, but it's not necessary a light, it can be with an other type of object, or just a position. What I want is to have an unlit image, with a movable circle zone on this texture which make the zone transparent, like the white circle on this picture (imagine that the with is just the transparency). The border shouldn't be necessarily with smooth border, it will be also fine with an hard border. I have thought about a spotlight, because it's like move a spotlight on the picture, but instead of doing the lighting, I want to set the "lighted" pixel transparent (but it's not lighted, it's just to explain what I want), a,d it's not necessary with a light And yes, the unlit shader can't do this I think, I probably need a custom shader but I don't know how to this (I have thinked about take a basic lighting shader, and use the computed intensity of the light on the pixels to set the alpha instead of use it to set the intensity of the pixel, but I don't know exactly how to do this)
|
0 |
How To Smoothly Animate From One Camera Position To Another The Question is basically self explanatory. I have a scene with many cameras and I'd like to smoothly switch from one to another. I am not looking for a cross fade effect but more to a camera moving and rotating the view in order to reach the next camera point of view and so on. To this end I have tried the following code firstCamera.transform.position.x Mathf.Lerp(firstCamera.transform.position.x, nextCamer.transform.position.x,Time.deltaTime smooth) firstCamera.transform.position.y Mathf.Lerp(firstCamera.transform.position.y, nextCamera.transform.position.y,Time.deltaTime smooth) firstCamera.transform.position.z Mathf.Lerp(firstCamera.transform.position.z, nextCamera.transform.position.z,Time.deltaTime smooth) firstCamera.transform.rotation.x Mathf.Lerp(firstCamera.transform.rotation.x, nextCamera.transform.rotation.x,Time.deltaTime smooth) firstCamera.transform.rotation.z Mathf.Lerp(firstCamera.transform.rotation.z, nextCamera.transform.rotation.z,Time.deltaTime smooth) firstCamera.transform.rotation.y Mathf.Lerp(firstCamera.transform.rotation.y, nextCamera.transform.rotation.y,Time.deltaTime smooth) But the result is actually not that good. Thank you all, I fixed it this way var pos Vector3 firstCamera.transform.position var rot Quaternion firstCamera.transform.rotation firstCamera.transform.position Vector3.Lerp(pos, nextCamera.transform.position,Time.deltaTime smooth) firstCamera.transform.rotation Quaternion.Lerp(rot, nextCamera.transform.rotation,Time.deltaTime smooth)
|
0 |
Throwing away inner faces of cubes of a transparent voxel structure in Unity3D? I want to create a "Building site is (not) obstructed." indicator for my building system. How can I throw away those faces which would be hidden if the material would be opaque?
|
0 |
Google Play Games Signs Out Automatically without Internet Unity I am using this in my game to implement games saving and loading. I have also tried the basic sign in process by using the following start function PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder () enables saving game progress. .EnableSavedGames () .Build () PlayGamesPlatform.InitializeInstance (config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate () Social.localUser.Authenticate ((bool success) gt if (success) MyAutoSave.isLoaded false ) I can sign in on google play games without any issues. Soon after that if I quit the game and start again without data connection, it gets authenticated without any issue. If my data connection remains off for say more than an hour, and I start the game without Internet connection, there is no authentication whatsoever. If I close the game and start again soon after that, it gives me that google play games sign in popup. So what i can conclude is that it signs out automatically after some time if there is no Internet available. Is there any fix for this.? Thanks
|
0 |
How does Unity Static batch handle submeshes I have the following 2 meshes Mesh 1 Submesh 1 Mat 1 Submesh 2 Mat 2 Mesh 2 Submesh 3 Mat 1 (same as mat1 from submesh 1) Since submesh 1 and 3 have the same material and they are all static, I'd like to render submesh 1 and 3 in a single drawcall. However, Unity is failing to batch those submeshes together. Is there a way to achieve this?
|
0 |
(Unity3D) Determine If Ray Intersects Given Rectangle I'm building a city generator for my game and I want to ensure buildings are never placed in such a way that they overlap roads. Currently I have the system build the roads, then place buildings alongside those roads. I have the beginning and end points of the roads as Vector3s (only using X and Z, Y is never considered for road building placement). For buildings, I use the size of their Box Colliders to check if they can fit in a given space (with rotation and scale applied appropriately). I've done a fair amount of research for answers on lines intersecting planes, though they always seem to be incredibly hard to follow or just don't properly apply to my situation (such as determining if the line is coterminous or not). I simply need to know if the line at any point exists within the bounds of the building's rectangle. I do not need to know where or at what angle. I also understand that my problem is essentially a 2D math problem, as I'm ignoring Y, and some of the 2D solutions I've seen to this would be extremely costly to do in city generation. Any help would be greatly appreciated.
|
0 |
How can I play and stop a Visual Effect Graph effect through script? Can anyone please give an example lines of code one could use to play stop a VFX through C script.
|
0 |
Support multiple gamepad layouts (Unity 2017.3) My game supports touchscreen, keyboard mouse and the Xbox One controller and the input so far works properly. Now I also want to add a second layout for the gamepad the player can then pick in the settings, e.g. Layout 1 Fly up with "A", fly down with "B" (so two buttons) Layout 2 Fly up with "LB", fly down with "LT" (LT uses an axis, not a button!) With keyboard touchscreen and gamepad input I was able to create two different inputs in Unity's InputManager for the same thing and they would then trigger depending on which input device you're using. I thought about adding a bool for the layouts and checking it every time a button is pressed but that sounds more like a quick and dirty solution. Descriptions of InputManagers I've found so far make it sound like they're used for rebinding keys or to support different gamepads (e.g. Xbox One and PS4), which I don't want need (plus, these InputManagers are usually pretty expensive). How do you handle actual different layouts that use the same buttons axis for different things, especially with something using a button in the first layout and an axis in the second?
|
0 |
Is making a sandbox feasible in Godot Unity (w o open world)? I want to make a 3D multiplayer game. It will inherit the basic principles of the MOBA genre players choose from the variety of characters each having 4 8 unique abilities, then battle it out. I also want some abilities to affect terrain. I try to keep the concept simple to be able to make this game alone. It would be good if I manage to finish the first playable prototype in no more than 6 months (keeping in mind that I'll be able to work on the game mostly on weekends). Multiplayer AND 3d in themselves make things much harder, so deciding which mechanics to implement and how is essential. Thus I want to make sure I won't have to redo much after I start programming. To implement the destructible terrain I decided to stick with a Minecraft ish approach, where everything consists of blocks. The sandbox is a very hard genre in terms of game development, but after doing quick research, I concluded that most difficulties arise from the fact that the game is open world. This isn't my case. I won't need too many blocks to construct the arenas. Now I need to come up with the engine I'm gonna use. I like Godot due to its development paradigm, but I'm not sure whether it is a good choice for a game like this. Maybe Unity is the better choice in my situation. Or something else. Maybe I need to remove some mechanics from the concept to make the development a lot faster. Can you comment on it? Thanks! P. S. I have 7 years' programming experience (with Haxe and Python being my main languages) and a good mathematical background. I have been developing my multiplayer game for 3 years now (but it is a 2D game, I have no experience in 3d gamedev beyond the Godot tutorial). It is okay if I need to learn different things before starting to make a game, but I want to make the learning process as effective as possible.
|
0 |
OnTriggerEnter is it called in both collider object? I've 2 object a Player and a Bonus object. In both script I've "OnTriggerEnter" script. In Player OnTrigger I Take Bonus value and add it to my Player (health, point, ammo) In Bonus OnTrigger I Play audio (when take it), Play Particle System and so on... But, it seems it's called only Player's OnTriggerEnter ... Why ? In Unity, if I have OnCollision OnTrigger enter in both object, which event is called ? Both ? Thanks
|
0 |
Creating multiple levels in Unity without duplicating scripts I'm trying to create a falling word typing game like z type. I have used the code provided here I want to create multiple levels in the game, and it seems like I need to make some changes in the code for each level. For example, in the word display file, I want the active word to be changed to red for level 1 and blue for level 2. So I created a copy of my level 1 scene, created a duplicate WordDisplay script file, changed the code for active word to blue.... public class WordDisplay MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.red ... Here's the duplicate script I made public class WordDisplay1 MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.blue ... Then I made a copy of the WordSpawner as well because I was getting an error I had to change the method's return type to to WordDisplay1 and then got one more error which was in the Word file, leading to more changes... public class WordSpawner MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay SpawnWord() ... public class WordSpawner1 MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay1 SpawnWord1() ... Then I created a duplicate of the word prefab and selected the appropriate word spawner file... All of this seems like too many changes for a simple colour. Is there a better way to have multiple levels without having to create a duplicate of all these files and the word prefab?
|
0 |
How to make a custom inspector component I have a script component, but I want to know how I can add things like sliders buttons etc. I wrote a grid system that generates at the start of my script but I want to run it in editor when I push a button to not to force calculations, lessen load times for my game and even see result of my work in editor. How can I do that?
|
0 |
How can I stop startcoroutine when pressing once on the escape key? I want like in games to pass over a cut scene or splash screen in this case. So the user can hit the escape key to pass it over. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using UnityEngine.Assertions.Must using UnityEngine.UI using UnityEngine.SceneManagement public class Splashes UnityEngine.MonoBehaviour Header("Splash Screen") public bool useSplashScreen true public GameObject splashesContent private List lt Graphic gt splashes new List lt Graphic gt () public float splashStayDiration 3f public float splashCrossFadeTime 1f void Start() if (!useSplashScreen splashesContent.GetComponentsInChildren lt Graphic gt (true).Length lt 0) return if we use splash screens and we have splash screens region Get All Splashes if you build on PC Standalone you can uncomment this foreach (var splash in splashesContent.GetComponentsInChildren lt Graphic gt (true).Where(splash gt splash ! splashesContent.GetComponent lt Graphic gt ())) splashes.Add(splash) for (var i 0 i lt splashesContent.GetComponentsInChildren lt Graphic gt (true).Length i ) var splash splashesContent.GetComponentsInChildren lt Graphic gt (true) i if (splash ! splashesContent.GetComponent lt Graphic gt ()) splashes.Add(splash) endregion And starting playing splashes StartCoroutine(PlayAllSplashes()) private IEnumerator PlayAllSplashes() Enabling Splashes root transform if (!splashesContent.activeSelf) splashesContent.SetActive(true) main loop for playing foreach (var t in splashes) t.gameObject.SetActive(true) t.canvasRenderer.SetAlpha(0.0f) t.CrossFadeAlpha(1, splashCrossFadeTime, false) yield return new WaitForSeconds(splashStayDiration splashCrossFadeTime) t.CrossFadeAlpha(0, splashCrossFadeTime, false) yield return new WaitForSeconds(splashCrossFadeTime) t.gameObject.SetActive(false) Smooth main menu enabling splashesContent.GetComponent lt Graphic gt ().CrossFadeAlpha(0, 0.5f, false) yield return new WaitForSeconds(0.5f) splashesContent.gameObject.SetActive(false) private void Update() if (Input.GetKeyDown(KeyCode.Escape)) public void ExitGame() Application.Quit() This splash is showing up each time the game is running. So I want to give the player the chance to press escape key to pass over it.
|
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 |
Unity joystick input acting strange After setting up my joystick axes in Unity and sweeping them around I find that the Y axis jumps to the opposite direction in certain positions. So, when I press up on the joystick, the input will often indicate that it's pointing down. It will also sometimes do this in the opposite direction. It's somehow tied to the x axis position, making it especially weird.
|
0 |
How to prevent Unity from triangulating faces of imported models? I have an object that will be rendered with a wireframe shader. This means that line between vertices in a model would be drawn. The problem is that Unity automatically triangulates all n gons in my models. I want these n gons to render as is. Is there a way to prevent this?
|
0 |
NullReferenceException Error For Respawning I am making an infinite runner game, and I am having issues with killing and respawning the player. I have a coroutine setup on the GameMaster objec which is the respawn and on the player I have a method that calls that coroutine. But when ever the player hits an enemy I get a Null Reference Exception and I am not sure why this is happining. Here is the entire error NullReferenceException Object reference not set to an instance of an object Player.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Script Player.cs 32) Here is the line that when I double click on the error it goes to. This line is on the player. StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) This is the method that the above line is in. This method is on the player. void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "Enemy") Debug.Log("HIT") Destroy(col.gameObject) StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) Here is the coroutine that the above method is trying to call. This method is on the GameMaster GameObject and this object never gets destoryed or setActive false. public IEnumerator RespawnPlayer() player.GetComponent lt SpriteRenderer gt ().enabled false player.GetComponent lt BoxCollider2D gt ().enabled false player.GetComponent lt movemnt gt ().enabled false yield return new WaitForSeconds(respawnDelay) adMenu.SetActive(true) If anybody can give any suggestions that would be great!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.