#archived-code-general
1 messages Β· Page 38 of 1
My pleasure! Like I said, I didn't test but those are the main ideas. I think my code fits to -1/+1 but it's late and I can be dumb.
Made another correction. :/
One issue that I can see cropping up is if our cameras ever join together or the splitscreen line ever shifts. Iβll need to talk to the programmers more to see whatβs the plan with that
Yeah, that's going to be a matter of perspective then, but in any case the position on the screen would be a visual source, so the general idea applies.
Not going to lie, I assumed something like this would happen as canvases be like this. I'm glad you figured it out so quick!
Is it a known behaviour for linerenderers that they sometimes add an empty vector3 at the end of the line? Or am I doing something wrong
List<Vector3> points = c.GetLine();
while (points.Contains(Vector3.zero))
points.Remove(Vector3.zero);
lr.SetPositions(points.ToArray());
lr.positionCount = points.Count;
as you can see, sometimes it just snaps to the top left(0,0) even though I should be removing any 0 points that are there
Some issues with the animator.
I reuse my hitboxes and for most attacks, I just position and shape them with keyframes since it's all visual and I can match it to the animations nicely.
I have an attack that's an explosion that will be larger depending on when you call it, and so I can't really animate that in keyframes. Instead I'm just trying to change the size of that hitbox in code.
Problem is, as far as I can see it, unity's animator tries to "enforce" its current state even if the current clip has no keyframes for that value, so long as any other clip did. So, whatever it was last set to, it will persist that. I had hoped the "Write Defaults" option in the animator window would let me decide this, but it doesn't.
Is there some option I'm mission that stops the animator from trying to control values that aren't keyframed in the current clip, or something?
I'm aware there are ways I could design around this, but I would rather solve this baffling behaviour if possible.
when debugging all of the locations in the points there are no empty vectors, but when I look at the positions on the linerenderer itself it does show an empty vector for a split second, I wanna know if I should be expecting this or if this is unintended behaviour and there's some fix for it
Hi guys, I have a problem with my WEBGL application. When I try to load a json file into the program, I sometimes get the following error: "Out of Memory, If you are the developer of this Content, try allocating more Memory to your WebGL in the WebGL Player Settings". I have already compressed the entire build from 200mb to 100mb, but the error still occurs. In the Json file there are PNGs as Base64 string, which are then converted and used as textures. It has nothing to do with the size of the json file, it just happens every few tries. Do you know how I can release more JS heap or empty the JS heap again after loading a json file? Unfortunately I am completely stuck and don't know what to do, also various forums and googling for the problem didn't help. Does anyone have any solutions or tips for me?
How big is the JSON file? Have you tried increasing the memory size in Player Settings like the error message suggests?
https://docs.unity3d.com/Manual/webgl-memory.html
The size always varies, but it is usually around 5MB. Unfortunately, the option to increase the memory size no longer exists, or I was too stupid to find it. I use 2020.3.32.f1 with URP.
if you change the size of the array it will add a 0,0 point by default I believe - are you possibly out of sync with when you add a new point & define the new point? looks like it may be a single frame wait occasionally between adding it and defining it
there shouldn't be any? at least not purposefully, I do need to do some A* pathfinding so maybe that takes longer than it expects, but the number should be the same still
sorry, worded that badly - it's positionCount, if it's out of sync with the length of the positions array you set it can default the null positions to 0,0
try setting it before SetPositions
otherwise I'd try attaching a debugger and inspecting the values at each step
hi, i have a problem with changing the start rotation of particles through script in unity
i just set it to a number and the actual rotation in game is completely different
does anyone know why?
Try setting a break point after printing and verifying the z component then in the inspector.
what do you mean with break point ?
A break point in your IDE to momentarily pause the application at the specific location.
here ?
Sure
Try logging the start rotation rather than the weapon to see if it's what you think it is.
Also note:
hmmm
so that's
why
it's weired because debugging the start rotation does return the constant value in degrees
Try giving it a radian value as what you've given it would be a radian value and likely not what you would be expecting.
as you can see in the code above, that's the only position where I set the positions and position count, they should never be out of sync
1 - Picture
2 - Windows background
3 - Unity editor
Is there a way to "fill image" in unity the way windows does with background? By cropping up and down and avoiding stretching?
This isn't a coding question.
Probably would not scale the image at all, but child it to a mask and scale the mask instead.
I'm sorry, in what section can I ask question like that?
Thank you
how can I make a list of types?
I assume you aren't asking "how to make a List" which would be: cs public List<int> numbers;(integer example)
nah I was thinking like a list of types like
List<anyType> possibleLinks = new List<anyType>();
possibleLinks.Add(typeof(int));
possibleLinks.Add(typeof(myOwnClass));
Type would be the acquired type from typeof
yes
If you want a list of the Type type, you make it a List<Type> as Dalphat suggested. If you want a list of any type, you make it a List<object>. If you want a list of a specific instance type, you make a list that has an interface as a type, and have the instance implement that type. Alternatively you specify a base type that is shared by the instances, should you have that.
is it safe to invoke event that is raised with this.CustomData argument after I call Destroy(this.gameObject) in previous line?
events don't care one lick about Unity's concept of object destruction
yeah, but IDK about object's internal state in next line of code after calling Destroy
nothing changes I guess?
nothing changes
it is merely marked for destruction inside the engine
i have a grid of variable length. How can I calculate a camera position so it will adjust size based on my grid size?
What is the difference between UnityEngine.AI.NavMeshSurface and Unity.AI.Navigation.NavMeshSurface and which one should I use?
how can I check which script is causing high performance hits?
and what line?
I have the profiler opened
the profiler breaks down how much time was spent in each method
you might have to turn on Deep Profiling to see everything you need
it's a breakdown of time spent in each method
my game is running at like 5 seconds per frame now π
i had to quit the project in task manager, it used up all my ram, something is wrong with a part of my code which makes my game so slow and im trying to figure it out
The profiler defaults to the Timeline view, but that view is mainly only useful when profiling multithreaded workloads. To identify what is taking the most time in a frame, the Hierarchy view is more useful.
look at such a frame in the profiler and see what's taking up the largest chunks of that time
Is there a way to use the color swatches in the editor in the code ? I tried to put the color preset library in a scriptable object but it is not accessible through script. Or maybe there's a better way to use the same colors in code as well as in editor that I am not aware of.
can you cache the boxed statement beforehand in a variable to make this line shorter?
https://i.imgur.com/mgAGVTg.png
how can I open hierarchy
not that statement but the whole lambda yes.
how to?
store it in a variable
Action<AsyncOperation> callback = <the whole lambda here>;
whatever.completed += callback;```
The dropdown is labeled "D" in this picture.
nice thanks
well there you go
probabably because im calling it every frame for every object.....
something is wrong then because I only made it call it when it doesnt have a path yet
congratulations you're on the path to fixing your problem now.
Has anyone had a similar problem using
I think it's because you are constantly updating the new transform rotation. You can either cache the original rotation and multiple by that, or instead add an offset to the angle so it lines up with your direction
when i save i set the save file's saveDate to DateTime.Now: Manager.instance.data.saveDate = DateTime.Now;
debug.logging it shows the correct time for both the saved date and datetime.now
when i load it: DateTimeoldTime = instance.data.saveDate; i get 1/1/0001, the default value of datetime
sounds like it's not being serialized properly
have you looked at what it looks like in your serialized representation?
Depending on which serialization framework you're using DateTime might not be supported out of the box
good point let me take a look
oh yeah it's not even in the file
saving it as a string and converting it seems to have done the trick, tyty :)
public class Ability
{
public float damage;
public Ability(float dmg)
{
damage = dmg;
}
public void use()
{
}
}``` hey, is there anyway i could pass a function in the constructor of my class, that would be run in use()?
action?
hmm yess
You'd have to describe it better than that
like how the body moves
Maybe look into Joints
and the sprites change
like the snake movement
Like a real snake?
one moment
this movement
pretend thats a snake
like the tail moves
where the player is moving
Use joints if you want a fully simulated snek
Or use bones & animations if that is enough
Or procedural animations
ok
say I generate a huge map via a script, ex) placing a bunch of enemies and tiles and objects
is there any way to save this to a scene?
i have a parent object for my NPCs, with a lod group and 2 different LOD levels / gameobjects within. I'm not sure where the animator component should be. Should i have one for each LOD? Or one in parent that controls both?
One in the parent that controls both
@severe maple One of the renderers can be on the parent too, its not an issue
Depending on the setup ofc.
thanks. When the lod level changes though the animation stops, I guess because it is still trying to animate the old mesh. I guess I have to code in some switcher?
Are you animating the renderer directly?
Like does your animation change the renderer's values
i dont think so
I don't think that a renderer getting disabled (by LOD) should make the animator stop π€
maybe something else is happening, I'll fiddle around, thanks
any chance you have a video or guide or something that descibes that well?
I wasn't able to find one
Hello!
I have a box with a rigid body component attached and a script that contains a variable inside of which the 'health' of the box is stored.
How can I determine if this box is being pushed against a static surface by another moving object, essentially crushing the box?
I want a way to determine when the box gets squeezed between two surfaces so I can destroy it.
colliders?
What about them?
@thick socket, you were saying?
just throw a collider on both objects then you can check like "OncollisionEnter" stuff
π
Doesnt really explain how to check if its being crushed between two objects
Yeah
You could gather the contact points from OnCollisionEnter (or OnCollisionStay) and do some calculations with those
can just keep track of if its colliding with something on say left, and also right
Check if a contact is on the other side of another etc
Unfortunately theres no builtin stuff for calculating stress
Its a rigidbody, not a softbody after all
So far, I was able to write some logic that determines when a collision takes place, stores the velocity of the box at the moment of impact and uses it to determine what amount should be subtracted from the box's "health". This way, if you keep throwing the box against a wall, for example, it will eventually break.
That sounds good.
If the player has a rigidbody, you can set it to kinematic, and manually update its position to stay with the car. Making it a child can work but im not sure
Oh he removed the question
Talking to myself like a dummy
I'll check to see if joints can be used to get the desired result. Thanks, @rigid island!
I swear!
this may be a dumb question but I wanted to ask what you guys thought would be the best option. I'm making a choose your own adventure game. A video clip plays, then buttons pop up, you vote on a path and then it goes there. so on and so forth. for playing the videos, I have an array of video clips. Then i just plug them into the video player.
My question is, what should I use for my array so that each video holds two ints. for example, the video at index 0 needs to hold two int variables 1 and 2. then video at index 1 needs to hold 3 and 4 while video 2 holds 5 and 6. If I could have each video in the array have its own variables attached that would be great but I don't know how to do that.
I'd probably use ScriptableObjects for this. Something like:
[CreateAssetMenu(filename="New VideoNode", path="MyGame/VideoNode")]
public class VideoNode : ScriptableObject {
public VideoClip Video;
public VideoNode[] NextOptions;
}```
Then your GameManager can just have:
```cs
public VideoNode StartNode;```
and you set up the choices on each SO itself
Parenting kinematic rigidbodies is fine, I believe, but any non-kinematic RBs in the hierarchy seem to cause very glitchy physics
I thought for sure RBs used to ignore motion inherited from parent, but apparently not
Yep non-kinematic rb is wonky when parented to another, but according to a recent test I did, a kinematic body seemed to stay fixed
ooo i see. do you have a good tutorial on script objects i could look into?
how did you get thumbnails on your array ?
like the video thumbnails to the left of the name? it just showed up when I dragged and dropped them in @potent sleet
Ohh I see, so it's built into unity like that for video array. π
it is nice lmao
Can I use BurstCompile in methods which access managed references?
What about methods which calls Unity apis, such as Physics.Raycast or MonoBehaviour.transform?
No
You can't use Burst compiled code outside the context of DOTS/the Job system. The code it generates is native code, which cannot run in the C# CLR.
.transform is a managed reference, and cannot be used in a Job/DOTS
Physics.Raycast cannot be used in a Job/DOTS, you must use https://docs.unity3d.com/ScriptReference/RaycastCommand.html - scheduling the raycasts as their own job.
https://docs.unity3d.com/Packages/com.unity.burst@0.2/manual/index.html
Burst does not support:
Any methods related to managed objects (e.g array access...etc.)
no
ok
You can actually BurstCompile static methods and call them normally in C#
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-calling-burst-code.html
hmm maybe that's newer. I was basing my answer off this https://forum.unity.com/threads/burst-and-thread-safe-api-outside-unity-jobs-system.522737/#post-3431626
Is possible to disable chekcs of NativeArray<T> an stuff in the editor outside Jobs? Jobs->Burst->Safety Check AFAIK is only for jobs using burst. What about non-jobs?
Burst uses IL post processing magic to replace your call with something else
I don't think the safety system ever applies outside of jobs
If I try to use a disposed NativeArray<T> outside a job I get an ObjectDiposedException, which means the safety is actually working.
you would have to be doing your own threading at that point for it to matter. In which case, why not use Jobs?
I'm writing instructions / reading output of a job in the main thread
that's not the safety system afaik, just a flag on the NativeArray π€
Well, is there a way to disable ENABLE_UNITY_COLLECTIONS_CHECKS?
the safety system statically analyzes your code and detects things like reading/writing from native collections in ways that are not inherently thread-safe
Oh, I didn't mean that then
further to my question earlier... how should I setup animator component for LODs on NPCs
I would have just one CharMaleGuard, but with the additional LOD meshes as children
You might need to export the lods with the main armature so that the bone weights get assigned properly. It can be tricky to do manually
Yep, no need for multiple armatures or animators. The LOD meshes can use the same armature no problem.
thanks
...or just duplicate the high poly model children and replace their meshes with the low poly ones
it works now, thank you
I have this RoomGenerator script but for some reason after the first GenerateNextRoom invocation, all the rooms start to spawn adjacent the first room ```csharp
public class RoomGenerator : MonoBehaviour
{
public RoomBase[] Rooms;
public readonly List<RoomBase> GeneratedRooms = new();
void Start()
{
GeneratedRooms.Add(Instantiate(Rooms[0].gameObject, Vector3.zero, Quaternion.identity).GetComponent<RoomBase>());
GenerateNextRoom();
}
public void GenerateNextRoom()
{
RoomBase lastRoom = GeneratedRooms.Last();
RoomBase room = Instantiate(Rooms[0].gameObject, Vector3.zero, Quaternion.identity).GetComponent<RoomBase>();
room.Number = GeneratedRooms.Count;
Vector3 entrancePosition = room.gameObject.transform.TransformPoint(room.Entrance.transform.position);
Vector3 exitPosition = lastRoom.gameObject.transform.TransformPoint(lastRoom.ExitDoor.transform.position);
room.transform.position = exitPosition - entrancePosition;
GeneratedRooms.Add(lastRoom);
}
}
The list is readonly π€
it doesn't have an effect on what I am doing here
since I am not re-assigning the GeneratedRooms field
Not sure if youre using TransformPoint correctly here
It converts from local to world space. But you are giving it world space positions
@quaint flame
who else noticed huge drop in performance in 2022.2? sluggish editor, any hiccup is now 2x larger
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
doesn't transform.position return relative coords?
That's world space.
transform.localPosition is relative to parent.
oooh
Hey, im making a shader and I have the script done, how do I make it so when the mouse is hovering over the object I gave the script, the object gets the outline? Here is the script for the outline : https://gdl.space/ikurimanik.cs
There's also this:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html
I dont remember when to use which
Hey, I just finished making some controls for two separate players in my project... but I'm running into two issues, and I'm hoping you all could possibly push me in the right direction so I can fix this:
-
When both player types are activated in the scene, both of their separate scripts take effect and cause movement. It doesn't matter which character is selected in the hierarchy to take control of the main camera in the game view, they both move.. and I guess I kinda expected this to happen but I'm not really good at figuring out why.
-
Eventually, after the first issue is fixed, I'd like to make the game run separate clients if that's possible to simulate two different players connecting at the same time. I understand there isn't a simple solution to something like this, so any referencing/information on the subject that retains to my situation is much appreciated!
well I changed it to room.transform.position = lastRoom.ExitDoor.transform.position - room.Entrance.transform.position; and the problem still persist
Well that looks wrong too
I am trying to make it so that the the position of the new room's entrance is the same as the exit of previous
Are the rooms ever rotated?
well not right now
// Position offset from last rooms center to exit
Vector3 exitOffset = lastRoom.ExitDoor.transform.position - lastRoom.transform.position;
// Position offset from entrance to new room
Vector3 entranceOffset = room.transform.position - room.Entrance.transform.position;
// Apply position by adding these two offsets to the last room's position
room.transform.position = lastRoom.transform.position + exitOffset + entranceOffset;```
My brain is fried atm but that could work
@quaint flame
Someone please save my hair. How can this cast work:
OneHandedObject weapon = (OneHandedObject)_item;
But this gives invalid cast
TwoHandedObject weapon = (TwoHandedObject)_item;
when both onehandedobject and twohandedobject derives from item object
oh right I wasn't adding them to lastRoom.transform.position that is most likely the problem lol
https://hastebin.com/share/vuzimisoke.csharp
hey so i have this action in the ability class that acts as a parameter so i can pass a function into the class. Now my problem is that after i closed down unity, and reopened, the functions of the abilities arent being ran anymore. I have no clue wtf happened in the time the project was closed, but it dont work.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Quite a long chunk of code, post it in a paste site
Because a TwoHandedObject isn't a OneHandedObject.
If you had an inheritance chain like this, it would work: Item <- OneHandedObject <- TwoHandedObject
But it seems you have Item <- OneHandedObject and Item <- TwoHandedObject. They both derive from the same class, but that does not mean they can be cast to each other.
the results are the same, but now that I know the problem I can fix it. Thanks for the help!
Same results? Thats weird π€
Ah thanks for the answer but both those are in different functions, and it sends the _item to different functions dependent on the type, so the flow is EITHER Item -> Onehanded OR Item -> TwoHanded
my code is a giant messy pile of poo atm, so I cant really post a sliver that would make sense
If you need to know the type to cast, then you're probably using inheritance improperly. Your method should be able to take any Item and call a method on it. C# will then select the correct implementation depending on what real type it is
Its true, I probably am notusing inheritance like I should, its the first time im getting into that stuff, I'm thinking maybe it would be better to just add an "twohanded" bool to a weaponobject and leave it at that for now
Having two-handedness as a property sounds better to me, than a separate class
I found the cause of the error :^ ) GeneratedRooms.Add(lastRoom); I was adding the same room to the list
<#archived-code-general message>
Oh lol! I read that a couple of times but didnt notice either
Well, the transformpoint was wrong too so that got fixed at least
I have a question, for the new input system, I have 4 multiplayer event systems set up (4 player game), and I want to choose which device corresponds to which event system (I have 1 keyboard/mouse and 3 ps4 controllers), how do I go about this?
you are at the start of a long journey
every multiplayer event system runs for every input. all UGUI handlers are called, eventually, from an Update in multiplayer event system. (1) multiple multiplayer event systems give you a distinct EventSystem.current.selectedObject, and ...
(2) it's your responsibility to ensure that player A can only interact with a specific UGUI hierarchy. you can do this using the Player Root Transform field. that's how the multiplayer event system rejects inputs from "other players"
does that make sense?
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
sorry about that
So I have this weird bug, where as i change states velocity from one state is "paused" until it enters that state again
For example, if I jump while moving right, then stop in midair and hit the ground, i move to the right a little
https://hatebin.com/hsgqrquffr air state
https://hatebin.com/lqgfrrjkfa ground state
https://hatebin.com/ooaidoouql state machine
not sure what is causing this
is there a way to like, transfer the velocity from one state to another?
I'm having an issue with my camera system, I have been trying to implement a system where it will follow a position in-between the mouse position and the target (player) for some reason this keeps going super far into the distance then stopping and behaving like normal
https://hastebin.com/share/omecegagop.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
(getting video for refrence)
float totalDistance = Vector2.Distance(new Vector2(0, downS.anchoredPosition.y), new Vector2(0, recS.anchoredPosition.y));
player1Icon.rectTransform.anchoredPosition = new Vector2(player1Icon.rectTransform.anchoredPosition.x, downS.anchoredPosition.y + (totalDistance * (elapsedTimerPercent / 100)));```
my UI wont move at all. what's wrong with my code. I've look all over for a solution.
im using urp and light 2d, everything works fine in the editor but when i build and run it, it doesnt work. are there any build settings i have to change?
whats not working
the lighting itself, like it never gets darker or lighter in the day cycle
but in the editor the lights work
so i wanted to make an inventory system for my game (unity 3d) however i've no idea how to do so, i made a scratch project (ik how cringe that sounds) but its just to show what i want it to look like, can anyone help
the hotbar is only 2 slots, a main hand and an off hand incase that wasnt obvious
i can link u to some videos i used if u want, drag and drop system, stacks, scriptable object items and stuff
thatd be great thank you!
https://www.youtube.com/watch?v=oJAE6CbsQQA&t=32s
this is a really great basic inventory and is what im using, i built some more on it bc it wasnt everything i needed. keep in mind there are no splitting stacks or right clicking to take 1 item in a stack in this inv system
πΒ @TamaraMakesGames building system video: https://youtu.be/G2w78Xk6UhU
π FREE assets download: https://www.patreon.com/posts/72631393?s=yt
π Support me and DOWNLOAD Unity project: https://www.patreon.com/posts/72632413?s=yt
This tutorial guide will show you how to create a full inventory system with draggable items, bottom toolbar, full inven...
also if u need a crafting system lmk i made one that works well with this inv system
yea idt 2d or 3d matters
Hey, does anyone know a good way to make a pathfinding system in 2D.
grab a off the shelf A*, or learn how one works at a place like here
https://www.redblobgames.com/pathfinding/a-star/introduction.html
or here https://www.youtube.com/watch?v=-L-WgKMFuhE&list=PLFt_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW
if you prefer video
Welcome to the first part in a series teaching pathfinding for video games. In this episode we take a look at the A* algorithm and how it works.
Some great A* learning resources:
http://theory.stanford.edu/~amitp/GameProgramming/
http://www.policyalmanac.org/games/aStarTutorial.htm
Source code: https://github.com/SebLague/Pathfinding
If you'd...
a star or navmesh is a good start. checkout a (or some) tutorials for each to see which way you want to go . . .
well A* and navmesh are not mutually exclusive for example unitys 3d pathfinding is A* running on a navmesh
I'm basically trying to make it so objects follow a specific path and for the possibility of thousands of them to do so on the screen do you think A* can do that
Or is it more for finding the quickest route
it always finds the shortest path based on the heuristic implemented
doing thousands of units at once to one destination might be better to go with dijkstra's since it can solve the whole grid for how to get from one node to a other
but also if unit count is that high you are hitting speceilzied cases so would want to look into how RTS games do pathfinding
Wouldn't it be easier and more efficient to just create a pre made path in the scene and for the object to follow it?
well that would depend on your goals
like if its a premade path in scene it cant responed to anything the player wants to happen
My game is a tower defense, so there aren't any obstacles you can place to change the path while the game is playing
ok so in that situation you would not want a pathfinding system at all
i would just have a list of transforms
So then my problem is moving the object around curves, because whenever I try to use a Bezier Curve the rotation is messed up and the object is always at 90 degrees on the Y
if that's the case, you just need a waypoint system. you can create waypoints that connect to other waypoints where you can mark the player's base as the end waypoint . . .
yeah, didn't know if they wanted to do it their own or just use unity's navmesh . . .
So just have a bunch of transforms?
how most would approach it
each waypoint is a transform, when you reach a transform it gets the next one in the list to start moving towards
Would that be the most efficient way do you think?
i would make a waypoint script and use a list of waypoints, that way you can customize how enemies move. one waypoint can have it's own list of waypoints and randomly choose the next waypoint to move to. this creates different paths and obstacles for the player. you can even allow certain enemiy types to travel a specific path . . .
I'm trying to make a 2D game and I'm having some issues with slopes. When the player is going up slopes, they float above ground and get launched in the air at the end. When the player is going down slopes, they fall instead of sticking to the surface of the slope. When standing still on a slope, the player slides down. Is there something I can add to the player controller script to fix this?
you can't really tell which way is most efficient until you try different methods and test them. you already have an approach (given) that the majority of people use . . .
Alr
Thanks for the help
increase the gravity on the players rigidbody component you can also add a physics2d material to add more friction
the reason its floating is bc your hitboxes are wrong
make sure they match up with the floor sprite
I have a particle system functioning as a thruster for a spaceship. The particle system starts whenever the accelerate button is held down and stops when it's not. However, if the particle system is left off for long enough for all of the particles to despawn, it will not start back up again. Anybody know why this is?
we would need to see your code
and the main module settings of your particle system
public void StartThrusters(InputAction.CallbackContext context)
{
Debug.Log("Starting Thrusters");
thrusters.Play();
}
public void StopThrusters(InputAction.CallbackContext context)
{
Debug.Log("Stopping Thrusters");
thrusters.Stop();
}
Pretty sure your particles will die and not start back again because of the "duration" param you have. It wont loop again for roughly 7 seconds after they die.
When you use Stop();, the cycle still finishes. So if you hit your thruster again before that 7 seconds is up it wont play yet
This configuration still gives the same problem
whether or not looping is turned on
What input do you have mapped to StopThrusters ?
And are your debug logs printing to console when they should be ?
You turned off looping btw. per your screen shot
I'm not completely sure why you have 2 separate action maps for start/stop. The callback context can detect phases of the input events to know when they are performed/started etc..
StartThruster is mapped to the button being pressed, Stop is being mapped to the button being released
How else would I set that up other than subscribing to started and performed?
This is correct and fine
I'm trying to display this render texture overlayed on the game geometry, and it's.... kiiiind of working? It seems to be making a sprite mesh and displaying that, rather than the actual texture, and I'm not sure why.
(This is just for debugging purposes atm, I wanna verify that my rendertexture's being rendered correctly)
Here's the code for how I'm setting that sprite to the rendertex
maskedBackground is the sprite in question
private void UpdateBackgroundMask()
{
Rect renderTexSize = new Rect(0, 0, 400, 400);
maskedBackground.sprite = null;
RenderTexture.active = backgroundMaskRenderTex;
GetComponent<Camera>().Render();
Texture2D tex = new Texture2D((int)renderTexSize.width, (int)renderTexSize.height);
tex.ReadPixels(renderTexSize, 0, 0);
tex.filterMode = FilterMode.Point;
RenderTexture.active = null;
maskedBackground.sprite = Sprite.Create(tex, renderTexSize, Vector2.one * 0.5f, 2);
//print(tex.width + " " + tex.height + " " + tex.GetPixel(0, 0));
}
How do i make it display the actual pixels? x3
oop, here's the texture it's actually reading
(hopefully)
Wdym by "texture it's actually reading"? Is that what the camera sees?
When the camera renders to the texture, that is what it sees
Its just excluding the sprite that is based off of what it sees
Where do you see it like that?
the white blob here is a sprite whose texture i an trying to set to the render texture
In that original screenshot i just left the blob in the texture, when in practice it is not visible during execution, and i wanted to clarify
So do you want it to be visible or not?
It should just be a copy of what's in this render texture, but for some reason it's displaying as that blob, and im not sure whats wrong, how to debug it, or even what to google xD
(magenta is transparent)
So you don't want the white blob..?
Then we're back to a few messages ago. Where do you see it like on the screenshot here:
#archived-code-general message
thats in the preview of the rendertex
Which render texture? It sounds like you have more than one at this point...
But there's only one in code.
It's the same one, just with the visibility of the blob toggled off
So you can toggle it off?
Then what's the problem?
Or do you mean that it's toggled off in the scene?
Im trying to display the contents of a RenderTexture on a SpriteRenderer for debugging purposes, that texture looks like this, and for some reason it's displaying as a white blob, rather than pixels
What pixels..?π
Is the white blob not made of pixels?
From what I understand, it seems like you have this map and the white blob both in your scene and you want to render to the texture only the map, is that correct?
for the new Input System, there is UnityEngine.InputSystem.InputDevice .... but I found for OpenXR inputs is UnityEngine.XR.InputDevices which is not the same. How would I get the UnityEngine.InputSystem.InputDevice for OpenXR?
var inputDevices = new List<UnityEngine.XR.InputDevice>(); UnityEngine.XR.InputDevices.GetDevices(inputDevices);
im pretty sure the map is being rendered to the texture properly, its a 400x400 image with 1px corresponding to 0.5 units, i believe my issue is in the step where i convert that texture to a sprite
But isn't the issue visible on the render texture itself..? What does it have to do with sprites?
I don't see any white blob here
What is the white blob?
And if you want the pink to be transparent, why not take this into photoshop and erase the pink?
a spriterenderer whose sprite isnt cooperating xD
I think there's a problem with explaining what the issue is...π
What does it have to do with sprite renderer now?
Literally where is the white blob in any of the photo's you've provided
my map looks like this and i have this render texture
i run this code on the rendertex
private void UpdateBackgroundMask()
{
Rect renderTexSize = new Rect(0, 0, 400, 400);
maskedBackground.sprite = null;
RenderTexture.active = backgroundMaskRenderTex;
GetComponent<Camera>().Render();
Texture2D tex = new Texture2D((int)renderTexSize.width, (int)renderTexSize.height);
tex.ReadPixels(renderTexSize, 0, 0);
tex.filterMode = FilterMode.Point;
RenderTexture.active = null;
maskedBackground.sprite = Sprite.Create(tex, renderTexSize, Vector2.one * 0.5f, 2);
//print(tex.width + " " + tex.height + " " + tex.GetPixel(0, 0));
}
Ok, so you want to render the map is it's looking in the scene into a render texture?
that sprite that i create in there looks like this for some reason lol
The sprite only displayed what's rendered into the render texture.
yes
And the render texture is what your camera sees
yes
So take a screenshot of how it looks like in the game view
If you can get this in the game scene, would it not make more sense to just make some game object in advanced like this that you can make visible when you need it instead of making a new sprite from scratch?
Thats the plan, i'm just pre-generating this sprite with code while editing
same goes for my game geometry, it's generated from a graph of points
Then the camera that you use to render the render texture.
You should be able to see it's preview
Okay, so it doesn't have any white blob
yes
At what point(where) does it appear?
It's what the sprite i create in here looks like
What does backgroundMaskRenderTex look like?
it's this one
But it's the same one that had the white blob..?
i moved the sprite renderer out of the view of that camera and regenerated its sprite based off of that image, and it still looks like a blob lol
Ok, that's a new piece information. What freaking sprite renderer?
Or was it not an answer to my previous question??
It's the thing displaying the blob sprite x3
omg i went into play mode and it generated correctly after that
aughhh
Mightve been a LoD thing?????
if i regen it in editor mode, it's a blob again
entering and exiting play mode fixes it >.>
Probably something's relying on the main camera rendering, and when the game tab is not open, it doesn't.π€·ββοΈ
Or not. Donno... Still don't entirely understand the issue...
hey! does anyone know why i'm getting these errors when using math.normalize or math.length?
code is as it follows:
foreach ((TransformAspect transformAspect, RefRO<Speed> speed, RefRW<PhysicsVelocity> physicsVelocity)
in SystemAPI.Query<TransformAspect, RefRO<Speed>, RefRW<PhysicsVelocity>>()) {
float xInput = Input.GetAxisRaw("Horizontal");
float yInput = Input.GetAxisRaw("Vertical");
float3 direction = math.normalize(new float3(xInput, yInput, 0f));
physicsVelocity.ValueRW.Linear = direction * speed.ValueRO.Value;
}```
I tried to normalize by using 1/length but math.length also ends up in these errors
Unity ver. 2022.2.6f1 and Mathematics ver. 1.2.6
Anybody know why sometimes my particles system will just... not go? when it says it's going? this happens both in game and in editor.
Dividing by 0 is unacceptable.
so the z can't be 0?
if so, there's no way to normalize it?
i see
should I use an if to check if it's zero before trying to normalize or there's a better alternative?
Check first
Hello! I just updated from Unity 2019.x to 2021.3.15f1 and ran into a lot of problems with my Coroutine functions. I want to make a flashbang for my 2D game where the player tosses the flashbang and a white circle in the UI is instantiated and faded into view quickly and then faded out of view slightly slower to make a flash effect. The code worked just fine before the update. Any ideas?
You just have some syntax errors, not related to your Unity version
should i just work through the 75 errors?
Most likely a single misplaced bracket is responsible for 70+ of them
lol alright thanks
I do see mismatched brackets in the file you shared
are the URP and HDRP source repos the best resource for learning the ins and outs of the SRP?
The package manuals are likely a better resource than reading code
woa! thank you so much! you were right!
hello everyone, I have a question about webgl and tasks... I keep getting the error that i am using more than one task (from the browser) how do I avoid that.... do I use all my await methods in a single function or what??
(i have many UnityWerRequest 's being used so i have to have several tasks)
Can you share the exact error?
sure just a moment
I think multithreading is not allowed in webgl by default. That being said, default async await in unity runs on the main thread...π€
fixed.loader.js:1 warning: 2 FS.syncfs operations in flight at once, probably just doing extra work
That's a warning not an error
But I'd guess it's from reading multiple files at once?
Is there any callstack or other messages before/after?
i used only await functions ... not a single coroutine
How is that relevant to what I said?
there are no files, I am just sending and receiving data on each unity web request
Playerprefs for example can do it
because i read before that coroutines use multithreading
oh
They absolutely do not
Unity in general does not use any multithreading
I assume Coroutines create some snapshot of where it left off when it reaches a yield
And each frame it is checked if it can continue on the main thread
Tasks in unity have been specifically altered to work like that too, as far as I know. In regular c# they are multithreaded. In Unity they are not
if coroutines were multithread you couldn't use them in browser
They don't create snapshots of anything. They just get registered in a list somewhere and the entry points to resume them in the game loop are well documented.
Yes, that is pretty much what I said
Either way it's stored in memory and resumed when it reaches whatever the yield wanted
ok i am reading the web page
and i will try to not use player prefs... I will see what to do
Depends on what Unity uses. Assuming it's webassembly, multithreading is not supported in there
You can use playerprefs, you might just be doing something uncouth, like calling Save too often
true. is it WA or JS ?forgot
I believe Unity ships itself with something custom made when it comes to the browser
I think WebAssembly is too new
But I never used browser Unity π€·
How can I get a list of all the connected input devices (keyboard, gamepad, xr devices...?) with the input system?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/api/UnityEngine.InputSystem.InputDevice.html
yeah its been JS, was about to say..WA would be cool
Oh nice
Look at the first property...
ooooooooh yes I am
ah, thanks!
Then that clears it, it is currently impossible to use multithreading
I want to trigger a function when a property is assigned with a new value. And I also want this property to be visible in the inspector. Is there a way to do it? If property have a setter it wont serialize, even with [SerializeField] or [property: SerializeField]. Maybe custom Editor can help somehow?
i think its [field: SerializeField]
You'd have to write a custom editor, or use NaughtyAttributes or Odin
Otherwise Unity will never invoke a property for you from the inspector
This syntax is correct to serialize it only for autoimplemented properties though
I might be clueless but what if
type oldValue;
void Update()
{
if (oldValue != value) Function ()
oldValue = value;
}
I was thinking about that. Not sure about performance costs if u will just start using this approach everywhere :o
Ye I may just be clueless
I'm reading a text about basic ai wandering behaviour
If it hits a wall, it needs to move elsewhere at a different angle
Text says "SphereCast()" is used over "RayCast()" since it needs to account for the size of the character.
What does this bit mean?
I know RayCast() fires an infinite ray from a point towards a given direction
same with SphereCast(), but with a sphere instead with an assigned radius var
So haven't you answered your question?
What are you confused about?
how does the SphereCast take into account the width of the character?
Think of it this way - if you want to check if you can squeeze through a tunnel, would you shine a laser pointer though it, or try to send a basketball through it?
By casting a sphere
ah
that makes much more sense since the basketball is closer in size to me than a laser
aye thanks
wouldn't it better to cast a capsule then?
Perhaps
If you're capsule shaped
CapsuleCast exists too
You can and should use whatever suits your needs
ooo gotcha, thanks man
Currently trying to call JoinPlayer from PlayerInputManager with OpenXR InputDevices.... but it returns null because playerInput.user.valid is false, What can cause this to be false?
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
public class CachingDic<K, V> : Dictionary<K, V>
{
// Number of items the cache can hold
private int capacity;
private Queue<K> accessTracker;
private Dictionary<K,int> duplicateCounter;
public CachingDic(int capacity)
{
this.capacity = capacity;
accessTracker = new Queue<K>();
duplicateCounter = new Dictionary<K, int>(this.capacity);
}
public void Cache(K key, V val)
{
//Add new entry
this.Add(key, val);
//Track ussage
accessTracker.Enqueue(key);
if(duplicateCounter.ContainsKey(key))
{
duplicateCounter[key]++;
}
else
{
duplicateCounter.Add(key,1);
}
//Remove oldest when capacity is reached
if (this.Count >= capacity)
{
K removeEntry;
do
{
removeEntry = accessTracker.Dequeue();
duplicateCounter[removeEntry]--;
}
while(duplicateCounter[removeEntry] != 0);
this.Remove(removeEntry);
duplicateCounter.Remove(removeEntry);
}
}
public V Get(K key) {
accessTracker.Enqueue(key);
duplicateCounter[key]++;
return this[key];
}
}
Hey I am using the code above to Cache chunks in my endless world game. I really wanted a data structure which automatically deletes the least used item when something new gets added. What do you guys think about this class is there a better way to do it, or are there any issues with my class ? I was a little surprised that there was no build in class for this purpose
@violet crown yourObject.transform.GetChild(0)
0 is the first child 1 the second and so on..
foreach (Transform child in transform)
//these are all the children.
CHILD
use a foreach loop on the object transform, use GetChild, or Find. there are tons of ways you can find online . . .
Do note that that is an error prone way of doing things, and Gets are slow.
If you (anzee) provide more context we can potentially provide a better solution
is there a way to check if the game is currently being run in a build version or the editor, cus I want to have some debug features but I always forget to remove them from the build?
You can put your debugs in a
#if UNITY_EDITOR
Debug.Log("In the editor");
#endif
thanks
sorry, completely forgot to respond yesterday, but yeah that worked. just setting the count before the positions fixed it. Personally I find it stupid that it works that way, you'd expect it to just set the positionCount when it sets the positions imo, but hey
Do you guys write variables with a capital letter on the start?
I use lower for every type of variable but I think that is better to use a capital for public variables whats your opinion?
c# has coding conventions you can look at. typically, PascalCase (with starting capital letter) denotes a class, interface, struct, constant variable, property, method, or event. camelCase (with starting lowercase letter) denotes a local variable, and private fields have an _ (underscore). you can check it out here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
Donβt underestimate chatgpt, that shit scares me. If yβall have any trouble try chatgpt first, i had a problem i could not figure out and iβve been having trouble for a couple days, threw it in chatgpt, fixed it in 30 seconds and now my script works
I do capital on every first letter of each word, camelcase just gross
itβs not right
hello, i'm using NuGet for Unity to be able to use Cryptlex C# API in unity, yesterday it was working but randomly today i'm getting this error, does anyone know what might be the cause of this?
hi , i want load .mp3 file from android OBB folder
this is my code error is cannot convert string to AudioClip
public AudioSource InGame_MusicPlayer_AudioSource; List<AudioClip> Music_Clip = new List<AudioClip>(); public AudioClip[] Array_AudioClip; // Start is called before the first frame update void Start() { Music_Clip.Clear(); Music_Clip.Add(Application.dataPath + "/" + "Music" + "*.mp3")as AudioClip); foreach (AudioClip clip in Music_Clip) { InGame_MusicPlayer_AudioSource.clip = clip; } }
ok I am making a mobile game... the android version is working perfectly... I copied the files and pasted them on a mac... and ran the game in the inspector... unity always crashes... any help on this? what could be the reason?? what must I do??
Debug it π Look in your Players.log, no idea where that is on a mac.
Music_Clip.Add(Application.dataPath + "/" + "Music" + "*.mp3")as AudioClip);
Where did you read that this was allowed? π€
I looked around the internet and couldnβt find a solution to this problem.
Code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Combat : MonoBehaviour
{
private Animator animator;
private Vector2 kickValue;
private Vector2 punchValue;
private void Awake()
{
animator = GetComponent<Animator>();
}
private void OnPunch(InputValue value)
{
punchValue = value.Get<Vector2>();
if (punchValue.x != 0 || punchValue.y != 0)
{
animator.SetFloat("X", punchValue.x);
animator.SetFloat("Y", punchValue.y);
animator.SetBool("isPunching", true);
}
else
{
animator.SetBool("isPunching", false);
}
Debug.Log("Punched");
}
private void OnKick(InputValue value)
{
kickValue = value.Get<Vector2>();
if (kickValue.x != 0 || kickValue.y != 0)
{
animator.SetFloat("X", kickValue.x);
animator.SetFloat("Y", kickValue.y);
animator.SetBool("isKicking", true);
}
else
{
animator.SetBool("isKicking", false);
}
Debug.Log("Kicked");
}
}
Error Message
InvalidOperationException: Cannot read value of type 'Vector2' from control '/Keyboard/z' bound to action 'InGame/Punch[/Keyboard/z]' (control is a 'KeyControl' with value type 'float')
UnityEngine.InputSystem.InputActionState.ReadValue[TValue] (System.Int32 bindingIndex, System.Int32 controlIndex, System.Boolean ignoreComposites) (at Library/PackageCache/com.unity.inputsystem@1.4.4/InputSystem/Actions/InputActionState.cs:2800)
UnityEngine.InputSystem.InputAction+CallbackContext.ReadValue[TValue] () (at Library/PackageCache/com.unity.inputsystem@1.4.4/InputSystem/Actions/InputAction.cs:1939)
UnityEngine.InputSystem.InputValue.Get[TValue] () (at Library/PackageCache/com.unity.inputsystem@1.4.4/InputSystem/Plugins/PlayerInput/InputValue.cs:44)
Combat.OnPunch (UnityEngine.InputSystem.InputValue value) (at Assets/Scripts/Combat.cs:21)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
it crashes... i can't find the player log .. i found the editor log and i didn't understand what's the error...
Suppose you can add some sort of initial weight to each key and add to this weight the more you use it. The other weights would then go down until it reaches some threshold upon which you can remove it?
So say item 1 and item 2 start with weight 100. Item 1 is selected, and the weight of 1 increases to 105, whilst 2's weight becomes 95
You now take item 2 and they both become 100 again
Well usually it says something in the line of `Error bla bla not found, or wrongly initialized". Is there nothing like that in the editor.log?
Maybe if the dictionary becomes too bloated you can also just remove the lowest weight
In an earlier version I did it like that i saved every new item together with the time stamp of when it got added but that meant on adding I always had to iterate the whole list.
I used a sortedList instead of queue back than but it was kind of slow
no... it only says shaders and the problem happens when i use a task (unity web request)
I need some help with my code, it is not moving the bones of the eyes at the moment and I don't know why it's not working: ```cs
using UnityEngine;
public class EyeControl : MonoBehaviour
{
public Transform headBone; // the head bone object
public Transform leftEyeBone; // the left eye bone object
public Transform rightEyeBone; // the right eye bone object
public Transform leftEye; // the left eye object
public Transform rightEye; // the right eye object
public Transform target; // the target object for the eyes to look at
public float eyeOffset = 0.1f; // how much to offset the eyes from the bone position
public float maxLookDistance = 10.0f; // the maximum distance that the eyes can look at
void Update()
{
// get the head bone rotation in world space
Quaternion headRotation = headBone.rotation;
// calculate the eye position and rotation based on the left eye bone position and rotation
Vector3 leftEyePosition = leftEyeBone.position + headRotation * Vector3.right * eyeOffset;
Quaternion leftEyeRotation = Quaternion.LookRotation(target.position - leftEyePosition, headRotation * leftEyeBone.up);
// set the left eye position and rotation
leftEye.position = leftEyePosition;
leftEye.rotation = leftEyeRotation;
// calculate the eye position and rotation based on the right eye bone position and rotation
Vector3 rightEyePosition = rightEyeBone.position + headRotation * Vector3.right * eyeOffset;
Quaternion rightEyeRotation = Quaternion.LookRotation(target.position - rightEyePosition, headRotation * rightEyeBone.up);
// set the right eye position and rotation
rightEye.position = rightEyePosition;
rightEye.rotation = rightEyeRotation;
}
}```
Bones were tested inside the engine and they work as expected, the code doesn't though.
Hi!
I have been trying to create a script, that checks for all possible target objects and then moves the object near them(NavMesAgent) and when it gets close the targets get deactivated.
It finds the first target just fine, but after that it just stops and doesn't go for the next target.
void Update()
{
near = Physics.OverlapSphere(transform.position, 5f);
if(near != null)
{
foreach (Collider item in near)
{
if (item.gameObject == currentTarget)
{
navMesh.Stop();
currentTarget.active = false;
MakeNewPath();
navMesh.Resume();
}
}
}
void MakeNewPath()
{
targets = Physics.OverlapSphere(transform.position, Mathf.Infinity);
foreach (Collider target in targets)
{
if (target.gameObject.transform != null && target.gameObject.active == true)
{
navMesh.CalculatePath(target.gameObject.transform.position, path);
navMesh.SetPath(path);
currentTarget = target.gameObject;
break;
}
}
}
}
okay, got it working. I forgot to add the check so the ground isnt included when selecting a target.
healthPoint--;
if (healthPoint <= 3)
{
animBoss.SetBool("SecondPhase", true);
}
if (healthPoint <= 2)
{
animBoss.SetBool("SecondPhase", false);
animBoss.SetBool("SecondAttack", true);
}```
hi guys, ok so the animation is default -> SecondPhase -> SecondAttack but when the healthpoints dropped below 2, the animation goes back to default AND second attack at the same time so the animations turns out weird. How do i just stick to the second attack animation? π¦
Well then I don't know, without an error there is nothing to fix.
can I share the file here @main shuttle
I htought maybe there's a needed step when opening the project with imac (bcause it was made with a windows)
this
Yeah just dump it in one of the code sites
document exceeds maximum length π
ok it is on pastofcode.. but how do I share it
ok it exceeds the limit there too
Hit save and copypaste the link
It seems to cut of too at the end.
i made sure it has the same ending
how do i assign particlesystem force over lifetime in script
read the error
it doesnt say, just read only
You can't assign anything to this field
Is there some Set... method you can use?
I.e. SetForceOverLifetime, idk
i dont think so
Then you're not supposed to adjust it
then i will find some other solution, thanks anyways!
Usually read only fields will have a seperate property or method that allows you to set them. if it does not exist there is a big chance it's not supposed to be adjusted or it's unsupported
what says read only
show the full error
You know Unity provides code examples for this kind of thing:
https://docs.unity3d.com/ScriptReference/ParticleSystem-forceOverLifetime.html
you would do well to follow the example.
are you using source control like git?
i read that but it did not help
it helps
it shows you how to properly write the syntax for this
you are not writing the syntax correctly
you are trying to assign something to that property, which is not how it works
you must do it like the example
it's telling you what the error is. try changing value.Get<Vector2>(); to value.Get<float>(); why would a keyboard key be vector2? i think you mean to build a compound input with axes
this is basic programming, maybe ask #π»βcode-beginner
I put it for detecting if the player is moving but now looking back I donβt think itβs neeeded
you should keep up with it! you are close
you should start writing comments in your code, like in plain english what you are trying to achieve first
If youβre talking to me I do
well don't delete the comments afterwards lol
Hi
Why is my Unity preferences resetting this setting? I set it to Visual Studio 2019 but it resets it to "By File Extension" which opens scripts in another editor.
Hey which one is the better thing to do?
private void Update()
{
if (!uiControls.isPaused)
{
UpdateMouseWheelDirection();
}
}
Or do the if statement in the method itself?
No difference, but I think having the if statement inside is neater to keep your Update method not so cluttered
yeah thats what i would do aswell
like
private void Bla(){
if (uiControls.isPaused) {return}
// Method itself
}
This would probably be best right? Or is this any different:
private void Bla(){
if (!uiControls.isPaused) {
// Method itself
}
}
Are those the same in terms of performance and everything or is there any difference?
In a lot of cases I prefer the early return, so that the method isn't terribly nested
Its the same
This is just a readability thing btw.
Yeah that makes sense.
Yeah i think i will do it like that from now on aswell
makes most sense i think
Can an array be used to swap a game object's model?
But I would assume if the model was drastically changed, you'd have to change the colliders in the code as well by similar means?
when it comes to this, your question should never be "is X more performant than Y" - that's a mistake I see a lot of newer devs make. In this situation, there is 0 difference - but in many similar situations (using a bool over an int, lists vs arrays, for vs foreach), the difference is often so negligible that it won't matter, and as such, shouldn't be your main consideration.
It's much better to focus on making your code as readable as possible, before worrying about performance. Not only will this make you a much better collaborator, but in a lot of cases, you will go back to some old code you wrote one day and be thankful it's coherent.
There's a lot to read when it comes to this subject, worth having a google
I am getting a problem with my character moving automatically by moving the cam more than 110 degree
Its a 3rd person kind of thing
did you ever open unity hub or unity as an adminisrtator?
do you have source control, like git?
I have git installed
do you use it in this project
no
Could be windows overwriting it with its file extension default
something in that thread will fix it
to some extent, though I think dismissing every decision as an optimisation problem to solve later isn't great either - just need to develop an experience of what areas will cause issues over time.
Making a huge grid? Probably good to think about what structure to use first and not develop half your game with reliance on if(myList.Contains(myTile))
How do I keep my player moving with this object without parenting it to the object? This is the best I can do
i meant when it comes to more fine optimisation - but even in that case, if you write cleanly, it will never really be difficult to improve the performance down the line. it's easy enough to profile and figure out for yourself where the performance critical areas of your code are - and keeping things readable makes it signficantly easier to process and refactor if you need to
i ofc don't disagree there are some performance considerations you should have from the get go, but there is a big difference between "which data structure is more performant" and "should i be calling this every frame". you should never try to optimise on such a granular level unless you absolutely have to
whats the best way to make a highly configurable ability system
i dont have different characters but each player has a class with different abilities depending on that class
Inheritance
is that related to abstract classes
Doesnβt have to
yeah, I'm being pedantic really, I just worry people hear "never ask if X is more performant than Y" and really take it to heart - I think it's an important thing to learn, it's just not the focus (and very common for people to worry about it more than they should or need to)
how does inheritance work ive never used it before?
like
Google is in a better state to explain it
fair enough
Its quite easy
but like
is it possible for all abilities to share a function
im trying to make a recharge function but all abilities dont recharge in the same way
you can use an abstract class to share common functionality to derived types, for your recharge you can also inherit from an interface to share that behavior
Thats the point of inheritance yes
Hello! I'm trying to load a csv file and I'm struggling. I made a Resources folder in assets and put my csv file in it. I've looked up everything I can think of to get it to work and it's still not working. Anyone have any ideas?
With Resources.Load you don't specify the file extension, if I remember correctly
Yep, it's mentioned in the docs for that method
in future, when you have a problem and you don't know why - log it
if you had done:
csvdata = Resources.Load<TextAsset>("csvfile.csv");
Debug.Log(csvdata.text);
you would have most likely seen that it's empty
Yes. I just couldn't figure out why it was empty. Thank you so much for your help!
Oh come on itβs good shit whatβs wrong with it?
Donβt rely on it obviously but itβs really good if youβre having some trouble
Unity keeps showing this warning every time I change a script with the game running. Is it anything to be concerned about, or is it just something to clear away?
it might give you some working code to copy but you likely won't learn anything and any more complex things will probably not be able to help you with. Also it's sometimes/often just wrong in fun and subtle ways
i mean it does help if you know c# so you can see how it works
and know if it woul
It means you had a script attached to an object in the scene, or in a prefab, but you deleted the code file from your Assets. Now Unity can't find it anymore.
It won't cause any gameplay issues, but you should look through each of the objects you have, and locate a component that has the same error in the Inspector
Ah, I'll check if I can find which one is missing
How do I make a reference get referenced automatically in my script? For example if I have this code:
public Animator anim;
void Start()
{
}
and then I add the script on a gameobject, I want the anim reference to automatically be referenced in the editor if there is an animator on the same gameobject, I'm not talking about GetComponent<>
use OnValidate()
And yes you would need to use GetComponent in it
note you should still do it in Awake() as well.
Generally though if you want that behavior - it's not really worth serializing the value.
just assign it in Awake and be done with it
I just wanna squeeze out the most performance possible because my system is already quite heavy
and it would be kinda easy and user friendly if the references got automatically assigned when the script is added
^^
Thanks a lot
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Help, I want to sort the files by recently modified but it doesn't work
Here is my code: https://hatebin.com/wrbrgscrqa
Try by assigning the direction vector directly to the object's forward (or whatever you consider as "forward"):
worldObj.transform.forward = localDir;
Yeah you can do that, and it'll compute the rotation needed for you
please help π¦
Well that seems overcomplicated for sorting by modification date.
By "modification date" you mean what Windows shows you in the Explorer, or something else?
im making a level editor and i want to sort the files br recently modified
You didn't answer my question
Unix time stamp
Where is that stored?
inside the .level file in line 6
probably not the best idea. e.g. if you use something like Steam Sync etc that will not match the actual modification date of the save file
or if you just moved/copied files around
what do you mean?
you need to sort out your save file format in geenral. This looks like chaos. You're just doing raw string manipulation
you should use some real structured format like JSON
Okay then loop through each file and skip 6 lines, read then parse the timestamp
Then with that you can build a timestamp + path pair, and sort using that
If you use a structured format it's as simple as like theSaveData.modificationDate
I looked through my scenes at each object but I don't see any missing scripts, and I don't have any prefabs just yet. Is there anything else this could be from?
But yeah agreed, JSON or any other structured format would be better here
also if you are going to sort your save files based on metadata you should probably save metadata like this in a small section of data at the head of the file
already thats what it does
So you don't have to load the entire save file just to read the modification date
i already made the level editor
is gonna be hard to remake its file structure
So you'll have to do with what you have for now
and now you are reaping what you have sewn by using a chaotic file format. At least you should make a wrapper class that handles all these nitty gritty internal details
so you don't have magic shit in your code like
if (CountLines(AllLevelContents[j]) < 4000 + 15
π±
lmao
and float.Parse(ReadLine(AllLevelContents[i], 6), NumberStyles.Any); π±
You can build a data structure that consists of the file path and the timestamp, then use some LINQ to sort it
countlines is already a function
?????
If the localDir changes then the object will rotate. You can't have either of them, that always works. You might have another script that overwrites the rotation soon after
hello, i am having trouble with checking for errors in the console. when i get some errors and try to click on them instead of showing more info on the error (like line and script etc), i get spammed with NullReferenceExceptions, clicking these will in most cases also spam the console, the second NullReferenceException semingly always being a exception. the only way to stop the messages from coming is to hide the errors temporarily. i am on 2022.2.6f, but i have had this problems on several earlier versions
nvm i fixed it
Now it is showing this error, which does not seem to lead to any sort of script or gameobject. Any suggestions?
Restart Unity if it bothers too much
do references of a script set in the editor get removed or something when adding that script via add component
cuz i put some prefabs in a script but when i add it during runtime it doesnt have those prefabs
When you use AddComponent you are creating a new instance of the script. There would not have been any possibility for any inspector references to be set to it since it didn't exist in the editor before you hit play
oh
well that kinda sucks is there a way to get a reference to a prefab in the files then?
Sure
make a prefab
what's more efficient: checking a text file every second to see if it exists or checking a value in a json file every second to see if it has stuff in it?
which has references to the other prefab. and instantiate that
or are they the same
neither
you should not be reading files over and over again
read the file once
store the data in memory in a way that is conducive to your query
and use that
the issue is that I have python code generating the stuff in the json
is there a better way to get the c# and python to communicate?
i tried collapsing the the errors and it seems like there are 4 types of messages generated, and only one can be clicked without creating more errors
is this a completely separate python process? You could have them communicate over TCP
yeah but also I'm trying to get it to work both on windows and mac
doesn't change anything
if you're starting the process from C# you can read its stdout output etc if you want
oh wait I didn't know that
oh wow that makes it way easier
ofc you'd have to do some multithreading to read this properly
thanks!
No issue, if you update the values of these vectors each time you want to calculate the direction, and that they represent world positions (accessed with anyTransform.position).
Note that as Vector3 is a value type, it gets copied when you pass it around with =. If the Transform of the original object changes, the vector (a copy) won't get automatically updated!
yeah it doesn't have to be super complicated it's just a chatgpt infinite breaking bad episode generator lmao
what I have now works fine but it's so cluttered
trying to simplify
i tried making a more simple test for my problem. i made a new scene, and added a new game object, and added a new script with the code seen in the attached photo. same thing happens
you never intiialized your list
you need:
private List<int> aList = new();```
Since the list is private, Unity will not initialize it for you
also your list is empty, therefore aList[0] is out of range
so - two problems π
i know. i was creating a error by choise. my problem is that i am fully unable to debug my game cause if i click error in the console this happens
ehhh restart Unity? Seems like a bug in the editor
What is the result if I try to access a missing point in an array? 0, null, an error, or something else?
Depends what you mean by "missing"
and what kind of "access" you are doing
and what the array consists of
As in I have a 1 element long string array and I try to access the third element
ArrayIndexOutOfRangeException will be thrown
The C# docs explain this
Yeah what I sometimes do when I dealt with some vector math, is drawing them in OnDrawGizmos(), so I can move the objects in the scene, and they would update. No need to run the game, as long as you can have the references in the scene directly
I see. So if I wanted to make it so it didn't throw an error I'd have to instead fill the array with placeholders, correct?
Or check if the index is out of range before trying to access it
i reset the layout, and i still get the problem. sigh. can't really work on my game when i can't even see what line and script is creating errors. guess i'l file a bug report and hope they answer quick, would suck to be locked out from working for a longer time
Oh yeah that would work, wouldn't it
I could just add an extra line or two and it should work perfectly. Thanks!
!bug
πͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
π If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click βReport a problem on this pageβ!
π‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
Reproduction steps: # Open the user attached project # Open the βSampleSceneβ scene # Enter the Play mode # Select the error in the ...
is this the same issue you have?
oh it is. unlocking the project tab fixed it. thanks a bunch
guess i'l try to update to 2023
Perfect. One more quick question - are the conditions in an If statement done sequentially so that I could make it like
if(PositionNumber < AnArray.Length && AnArray[PositionNumber]) { stuff }
or are they simultaneous and I should use nested ifs??
Wait never mind, this shouldn't matter, I was taking the wrong approach from the start.
I was overthinking a simple problem
On a chain of operations with equal precedence (eg. a && b && c), then left-to-right.
That makes sense.
Though && is smart, it's short-circuiting. Meaning if what's on the left is false, it doesn't even look at what's on the right
As false AND <anything> is false
For some reason I was thinking my "exclusionlist" array would have matching values with my other array, but I can instead do this much easier using exclusionlist.Contains(item)
question about odin inspector. if i have a [ToggleGroup] attribute, i know i can set it to not close other toggle groups if it's expanded, but i also want like an [ExpandIf] the togglegroup is checked, and auto-collapse when it's unchecked. is that possible?
this works yes. && is a "short circuiting operator" so if the first one is false it will not execute the second one.
If you used & instead of && it wouldn't work
It appears that || works similarly too.
yep
Oh how do you do the in-line code block?
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
It appears that || works similarly too
Ah perfect
What happened to pastebin? I used to see it used for like everything but it seems like nobody uses it anymore.
pastebin sucks, it's full of ads and doesn't automatically do syntax highlighting so if someone doesn't explicitly set the language it won't do it at all making it even more of a pain to read the code
Makes sense, thanks
Is there a way I can have a list in the inspector with 2 types? I want you to be able to enable or disable a bool on a element in the inspector and there to be a dropdown for if you enable it and I'd like both to be next to the "element" in the list
make a struct with the two types and have a list of that
make a custom struct, mark it serializable, make that the type fo the list
irrelevant
ok?
just do it
ill try
they wont bite
Idk they're looking at me menacingly
they are very cuddly if you get to know them
think of structs like dogs, they always want to stay with you, very loyal, and classes are like cats, who always go wandering about and get lost and fed by other people
Now I want to know this analogy but with namespaces
namespaces and?
if structs are dogs and classes are cats then namespaces are houses
I see
Whats your car? What gets you from place to place
Knowing that might actually be useful
its more about character, not functional analogy
Ah aight
your car is a properly configured IDE
Oh yea fair enough
a 747 is kubernetes
kubernetes?
more like a jet xD
i mean, its impossible to maintain yourself but gets you fast to all major destinations together with 500 other people that have similar concerns
haha fair enuff. just thought jets would be more difficult than 747
When setting an object that's a child's rotation, is there a way I can make the position set be relative to the main object
oh man im stuck
how about nugets are helicopters
Never mind, I just need to set localRotation
Thought those would be supply drops from planes
maybe they are artillery strikes
not very accurate, but quick and on demand hitting the general area of the problem
Waiiiit is a struct kind of like a tiny class?
also lots of collateral damage when used haphazardly
structs are value types while classes are reference types, but defining them is almost identical
ok
structs constructor forces you to assign fields iirc
yeah cannot have a default field initializer in a struct until c# 10 (which unity does not yet use)
don't listen to the experts (or the gpt)
why
they give you too many details
fair enough
for your purpose, you dont actuall need structs
so the difference is irrelevant to you
we just suggested structs because they are optimal for your use case, but that doesnt really matter
idk how tf to use them for what im trying to do
literally all you need is something like
[System.Serializable]
public struct MyListObject
{
public SomeObjectType Thing;
public bool Enabled;
}
you listened to the wrong expert π
Lol
on the other hand, you wont ever again forget that attribute now
Yea
you are most likely constantly using structs without realizing it eg, Vector2/3 etc.
oh
oh, if you want the side-by-side display of the toggle and the reference, you need to make a custom inspector
oh
yea I dont really want to do that
I serialized the struct but it still not showing up
where are you using the struct ?
wdym
you need to use it somewhere in script to show in inspector
hey there we go
use like this
public class Bar : MonoBehaviour {
[System.Serializable]
public struct MyListObject
{
public SomeObjectType Thing;
public bool Enabled;
}
[SerializeField] private List<MyListObject> foo;
}
Yea
how do I add to the list?
Considering the list type needs to be the struct
in the inspector you can press the + button on the list to add a new element
in the script
in the code you just call .Add and pass a MyListObject in
you're trying to pass a GameObject not an instance of your struct
how do I add the gameobject to the struct, and have it add on validate
you don't because you didn't give the struct a field to store a gameobject in, your struct only has a field for your enum and a bool
is this your first time using any type in c#?
Item is a list
Your current class needs a reference to an instance of the InvMenuButton which can access the InvMenuButton.RestrictSlot (hopefully you have a member variable of this type in that class)
or your current class needs a list of InvMenuButton.RestrictSlot's
Not positive what you're goin for
would it make it easier for you to understand if RestrictSlot was a class? if so, make it a class. literally nothing will change except it will suddenly be a reference type instead of a value type but hopefully you'll at least understand how to use it
seems a bit passive aggressive
the statement makes sense , if you know how to use a class just change struct to class
Aight
can you send your current script https://hatebin.com
I kind of want to learn how to use structs though
Better then just living off classes instead when I could use structs
ItemType is the list of structs
so add to that
you almost had it the first time
I tried to but the list type is restrictslot so I cant add the gameobject to it
because you're missing GameObject in the struct
you would need to make a new struct to add to the list tho
oh
do you understand how it works if you make it a class?
yea but
congrats, you know how to use it when it is a struct then
the only difference is that a struct is a value type and passed by copy rather than reference
stack v heap too
var newItem = new RestrictSlot();
newItem.Item.Add(ButtonList[i].gameObject);
ItemType.Add(newItem);```
RestrictSlot needs a GameObject `gameobjectitem ` field
not important in this case because it's being stored in a List as a field which means the instances will live on the heap anyway as part of the List object
wait wtf, why did you make the class inherit from your monobehaviour?
yea idk
change it back to struct, look my example
instead of RestrictSlot.Item.Add(ButtonList[i].gameObject); I guess
I kinda tuned last minute so idk what ur trying to do, just showing you how to add to whatever struct u made xD
That'll work until he finds out to move var newItem = new RestrictSlot(); into the awake loop and cache it
what
don't do that
ok
you want to add separate instances of the RestrictSlot object into your list
Figured he wanted a List<RestrictSlot> slots and he'd have to create it in the awake()
ignore me
they already have a serialized list of RestrictedSlot
their issue was creating the instances to add to the list
Why is it saying Item isn't set to an instance of an object
Its to do with the NewRestriction.Item.Count
u need to New() a list
why does that even need to be a List?
I'm guessing you're doing something with items and inventory, shouldn't use GameObject either
because theres multiple gameobjects im trying to add to it
make scriptable objects
why
yes, but isn't that object supposed to represent one slot?
yea
so you want to put multiple gameobjects into one slot?
or do you want multiple slots each with their own gameobject?
so don't make that a list, that's why you have a List of the RestrictSlot object
to fix the null list you could add a constructor for RestrictSlot that takes in a list and assigns it
it shouldn't be a List anyway so that's not necessary. if it did need to be a List then that would be the solution, yes
It works
show the current code so we can make sure there wasn't anything else you missed
ah lovely, so you're just reusing the same instance of the RestrictSlot object, changing its variables and adding it to the list instead of creating new instances of the object like the code that Null gave you does
is that sarcasm?
there was a reason why i used var
the "ah lovely" part was, yes. the rest was obviously pointing out your issue
maybe I should've explained why I used var in a loop xD
i even pointed out that you shouldn't make that object a field and that you should be creating new instances of it and you said "ok" implying that you were going to leave the code as it was given to you
there you go. now i recommend changing if (ItemType.Count < ButtonList.Count) to if(ItemType.Count != ButtonList.Count) then clearing the ItemType list before that inner loop. then you won't have issues where ItemType is larger than ButtonList with extra objects in it
should probably do the same thing with the first if statement as well
[Version control question, lmk if there is a better channel to ask]
I don't want my Library folder to be commited/pushed in git. I have in my gitignore
/Spider/[Ll]ibrary/
/Spider/[Tt]emp/
/Spider/[Oo]bj/
/Spider/[Bb]uild/
/Spider/[Bb]uilds/
/Spider/[Ll]ogs/
/Spider/[Uu]ser[Ss]ettings/
...
But I still get an error that files form within the Library folder are too big. I am using git lfs and have initialized it (I can see files be uploaded)
I have tried moving the gitfolder into the project folder and removing /spider
I also made sure to refresh the cache.
Any ways around this?
did you commit the gitignore file before the library folder/rest of the project?
I refreshed the cache with git rm -r --cached . then did a git add . then a commit. Should I add and commit only the .gitignore first?
yeah
Ok I am trying to push with just a .gitignore commit.
But maybe its also pushing past commits that are an issue...
same error, ill look into removing old commits
Fixed by using git reset HEAD^ to undo commits (while keeping changes)
How could I get what index one of the slots is in the ItemType list?
IndexOf
A bit more complicated then that
in what way
so is an integer yet you can still use IndexOf on List<int>
Im trying to get the index of the gameobject though
like which element its under
where it is in the list
there's a few options. the most beginner friendly is just to loop through the list yourself
for or foreach?
which one do you think would allow you to get the index?
for
idk how exactly to do this though
I have it going through the list
Ah that works
Anyone have ideas why fileName won't bind in the path definition?
Feels like it should work. Just declaring a simple fileName and binding it based on what object I'm holding in my parent (w) class
it is only assigned a value if one of those three if statements is true. what happens when none of them are?
also you should ideally be using Path.Combine or Path.Join to create a path rather than concatenating strings manually
@somber nacelle thanks for the suggestion. I wrapped it in a conditional check and used combine but it didn't fix it
it's still unassigned
although I wouldn't recommend because it's not the cleanest solution, string fileName = string.Empty at the top would fix
rather than wrapping all of that in the conditional, use else if for your if statements then return and/or throw an error in a final else statement
uh boxfriend, it wont let me turn on and off the bool
show what you tried