#archived-code-general

1 messages Β· Page 38 of 1

lime hearth
#

I really appreciate it

earnest epoch
#

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. :/

lime hearth
#

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

earnest epoch
#

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!

dense ridge
#

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;
wary basin
#

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.

dense ridge
feral jasper
#

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?

late lion
feral jasper
mental rover
dense ridge
#

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

mental rover
#

try setting it before SetPositions

#

otherwise I'd try attaching a debugger and inspecting the values at each step

pale ore
#

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?

dusk apex
#

Try setting a break point after printing and verifying the z component then in the inspector.

pale ore
#

what do you mean with break point ?

dusk apex
pale ore
#

here ?

dusk apex
#

Sure

dusk apex
# pale ore

Try logging the start rotation rather than the weapon to see if it's what you think it is.

#

Also note:

pale ore
#

hmmm

#

so that's

#

why

#

it's weired because debugging the start rotation does return the constant value in degrees

dusk apex
#

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.

pale ore
#

ok a basic radian convertion made the trick

#

thank you

dense ridge
thin kernel
#

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?

vagrant blade
#

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.

thin kernel
vagrant blade
thin kernel
#

Thank you

simple mountain
#

how can I make a list of types?

dusk apex
simple mountain
#

nah I was thinking like a list of types like
List<anyType> possibleLinks = new List<anyType>();
possibleLinks.Add(typeof(int));
possibleLinks.Add(typeof(myOwnClass));

dusk apex
#

Type would be the acquired type from typeof

simple mountain
#

yes

dusk apex
#

System.Type to be specific.

thin aurora
hollow cliff
#

is it safe to invoke event that is raised with this.CustomData argument after I call Destroy(this.gameObject) in previous line?

leaden ice
hollow cliff
#

yeah, but IDK about object's internal state in next line of code after calling Destroy

#

nothing changes I guess?

leaden ice
#

it is merely marked for destruction inside the engine

icy sundial
#

i have a grid of variable length. How can I calculate a camera position so it will adjust size based on my grid size?

neon plank
#

What is the difference between UnityEngine.AI.NavMeshSurface and Unity.AI.Navigation.NavMeshSurface and which one should I use?

whole yew
#

how can I check which script is causing high performance hits?

#

and what line?

#

I have the profiler opened

leaden ice
#

you might have to turn on Deep Profiling to see everything you need

whole yew
#

im a bit confused what im looking at though lol

#

I just clicked the deep profiler

leaden ice
whole yew
#

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

late lion
#

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.

leaden ice
lone cedar
#

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.

swift falcon
leaden ice
swift falcon
#

how to?

leaden ice
#
Action<AsyncOperation> callback = <the whole lambda here>;
whatever.completed += callback;```
late lion
whole yew
#

found the culprit πŸ˜‚

leaden ice
whole yew
#

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

leaden ice
silk horizon
#

Has anyone had a similar problem using

pulsar ivy
#

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

swift falcon
#

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

leaden ice
#

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

swift falcon
#

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 :)

glass blade
#
    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

grand hemlock
#

guys how can i make sort of snake physics?

#

i have no idea where to start

hexed pecan
grand hemlock
#

like how the body moves

hexed pecan
#

Maybe look into Joints

grand hemlock
#

and the sprites change

hexed pecan
#

So like an old Nokia snake game?

#

Or physics based?

grand hemlock
#

nonono

#

nokia snake physics is a simple loop

grand hemlock
hexed pecan
grand hemlock
#

one moment

#

this movement

#

pretend thats a snake

#

like the tail moves

#

where the player is moving

hexed pecan
#

Use joints if you want a fully simulated snek
Or use bones & animations if that is enough

#

Or procedural animations

grand hemlock
#

ok

thick socket
#

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?

severe maple
#

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?

hexed pecan
#

@severe maple One of the renderers can be on the parent too, its not an issue

#

Depending on the setup ofc.

severe maple
hexed pecan
#

Like does your animation change the renderer's values

severe maple
#

i dont think so

hexed pecan
#

I don't think that a renderer getting disabled (by LOD) should make the animator stop πŸ€”

severe maple
#

maybe something else is happening, I'll fiddle around, thanks

thick socket
#

any chance you have a video or guide or something that descibes that well?

#

I wasn't able to find one

vivid remnant
#

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.

vivid remnant
#

What about them?

thick socket
#

ah cool thanks

#

I know very little about editor stuff πŸ˜„

vivid remnant
#

@thick socket, you were saying?

thick socket
#

πŸ˜„

hexed pecan
hexed pecan
# vivid remnant Yeah

You could gather the contact points from OnCollisionEnter (or OnCollisionStay) and do some calculations with those

thick socket
#

can just keep track of if its colliding with something on say left, and also right

hexed pecan
#

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

vivid remnant
#

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.

hexed pecan
#

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

vivid remnant
#

I'll check to see if joints can be used to get the desired result. Thanks, @rigid island!

hexed pecan
#

I swear!

fallen lotus
#

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.

leaden ice
#

and you set up the choices on each SO itself

vestal geode
hexed pecan
fallen lotus
potent sleet
fallen lotus
#

like the video thumbnails to the left of the name? it just showed up when I dragged and dropped them in @potent sleet

potent sleet
neon plank
#

Can I use BurstCompile in methods which access managed references?
What about methods which calls Unity apis, such as Physics.Raycast or MonoBehaviour.transform?

leaden ice
somber nacelle
neon plank
#

ok

leaden ice
neon plank
#

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?

late lion
#

Burst uses IL post processing magic to replace your call with something else

leaden ice
neon plank
#

If I try to use a disposed NativeArray<T> outside a job I get an ObjectDiposedException, which means the safety is actually working.

leaden ice
#

you would have to be doing your own threading at that point for it to matter. In which case, why not use Jobs?

neon plank
leaden ice
neon plank
#

Well, is there a way to disable ENABLE_UNITY_COLLECTIONS_CHECKS?

leaden ice
severe maple
#

further to my question earlier... how should I setup animator component for LODs on NPCs

hexed pecan
severe maple
#

ah just one arma?

#

that makes sense

hexed pecan
#

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

hexed pecan
severe maple
#

thanks

hexed pecan
quaint flame
#

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);
}

}

hexed pecan
quaint flame
#

since I am not re-assigning the GeneratedRooms field

hexed pecan
#

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

visual flare
#

who else noticed huge drop in performance in 2022.2? sluggish editor, any hiccup is now 2x larger

molten isle
#

!code

tawny elkBOT
#
Posting 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.

quaint flame
hexed pecan
quaint flame
#

oooh

molten isle
#

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

silent basin
#

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:

  1. 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.

  2. 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!

quaint flame
quaint flame
#

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

hexed pecan
#

Are the rooms ever rotated?

quaint flame
#

well not right now

hexed pecan
#
// 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

spare dove
#

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

quaint flame
hexed pecan
#

Mhm

#

It's easier when you break it into these positions and offsets

glass blade
#

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.

hexed pecan
simple egret
quaint flame
hexed pecan
spare dove
#

my code is a giant messy pile of poo atm, so I cant really post a sliver that would make sense

simple egret
#

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

spare dove
#

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

hexed pecan
#

Having two-handedness as a property sounds better to me, than a separate class

quaint flame
hexed pecan
#

Well, the transformpoint was wrong too so that got fixed at least

quaint flame
#

yeah now it works like a charm

#

thanks

mild wolf
#

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?

polar marten
#

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?

somber nacelle
#

!code

tawny elkBOT
#
Posting 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.

dim canopy
#

sorry about that

marble halo
#

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

#

not sure what is causing this

#

is there a way to like, transfer the velocity from one state to another?

dim canopy
#

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

#

(getting video for refrence)

wise hollow
#
            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.

sweet perch
#

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?

wise hollow
#

whats not working

sweet perch
#

the lighting itself, like it never gets darker or lighter in the day cycle

#

but in the editor the lights work

solemn grove
#

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

solemn grove
sweet perch
#

i can link u to some videos i used if u want, drag and drop system, stacks, scriptable object items and stuff

solemn grove
#

thatd be great thank you!

sweet perch
#

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...

β–Ά Play video
#

also if u need a crafting system lmk i made one that works well with this inv system

solemn grove
#

ty

#

do uk if thatd work with unity 3d

sweet perch
#

yea idt 2d or 3d matters

upper turtle
#

Hey, does anyone know a good way to make a pathfinding system in 2D.

quaint rock
#

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...

β–Ά Play video
rain minnow
quaint rock
upper turtle
#

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

quaint rock
#

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

upper turtle
#

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?

quaint rock
#

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

upper turtle
#

My game is a tower defense, so there aren't any obstacles you can place to change the path while the game is playing

quaint rock
#

ok so in that situation you would not want a pathfinding system at all

#

i would just have a list of transforms

upper turtle
#

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

rain minnow
rain minnow
upper turtle
#

So just have a bunch of transforms?

quaint rock
#

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

upper turtle
#

Would that be the most efficient way do you think?

rain minnow
#

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 . . .

vapid trout
#

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?

rain minnow
vagrant agate
solemn grove
#

make sure they match up with the floor sprite

thin frigate
#

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?

vagrant agate
#

and the main module settings of your particle system

thin frigate
# vagrant agate we would need to see your code

public void StartThrusters(InputAction.CallbackContext context)
{
Debug.Log("Starting Thrusters");
thrusters.Play();
}

public void StopThrusters(InputAction.CallbackContext context)
{
    Debug.Log("Stopping Thrusters");
    thrusters.Stop();
}
vagrant agate
#

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

thin frigate
#

This configuration still gives the same problem

#

whether or not looping is turned on

vagrant agate
#

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..

thin frigate
#

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?

low arrow
#

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)

cosmic rain
low arrow
#

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

cosmic rain
#

Where do you see it like that?

low arrow
#

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

cosmic rain
#

So do you want it to be visible or not?

low arrow
#

(magenta is transparent)

cosmic rain
#

So you don't want the white blob..?

low arrow
#

No lol

#

it should be the pixelated version of the map in that second texture

cosmic rain
low arrow
#

thats in the preview of the rendertex

cosmic rain
#

Which render texture? It sounds like you have more than one at this point...

#

But there's only one in code.

low arrow
#

It's the same one, just with the visibility of the blob toggled off

cosmic rain
#

So you can toggle it off?

#

Then what's the problem?

#

Or do you mean that it's toggled off in the scene?

low arrow
cosmic rain
#

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?

junior bobcat
#

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);
low arrow
cosmic rain
low arrow
#

the white blob shouldd look something like this

#

overlayed onto the map

cosmic rain
#

I don't see any white blob here

thin frigate
#

What is the white blob?

#

And if you want the pink to be transparent, why not take this into photoshop and erase the pink?

low arrow
cosmic rain
#

I think there's a problem with explaining what the issue is...πŸ˜…

#

What does it have to do with sprite renderer now?

thin frigate
low arrow
#

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));
    }
cosmic rain
#

Ok, so you want to render the map is it's looking in the scene into a render texture?

low arrow
#

that sprite that i create in there looks like this for some reason lol

cosmic rain
low arrow
#

yes

cosmic rain
#

And the render texture is what your camera sees

low arrow
#

yes

cosmic rain
#

So take a screenshot of how it looks like in the game view

thin frigate
low arrow
#

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

cosmic rain
low arrow
#

It's not the main camera, that one looks like this

cosmic rain
#

Then the camera that you use to render the render texture.

#

You should be able to see it's preview

low arrow
#

yep

cosmic rain
#

Okay, so it doesn't have any white blob

low arrow
#

yes

cosmic rain
#

At what point(where) does it appear?

low arrow
cosmic rain
#

What does backgroundMaskRenderTex look like?

low arrow
cosmic rain
#

But it's the same one that had the white blob..?

low arrow
#

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

cosmic rain
#

Ok, that's a new piece information. What freaking sprite renderer?

#

Or was it not an answer to my previous question??

low arrow
#

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 >.>

cosmic rain
#

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...

low arrow
#

not gonna look a gift horse in the mouth ig

#

this is weeeird

naive horizon
#

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

thin frigate
#

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.

naive horizon
#

if so, there's no way to normalize it?

leaden ice
#

You can't normalize the zero vector, no

#

That's meaningless

naive horizon
#

i see

#

should I use an if to check if it's zero before trying to normalize or there's a better alternative?

leaden ice
#

Check first

naive horizon
#

ok, will do it

#

thank you!!

cosmic quest
#

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?

leaden ice
cosmic quest
#

should i just work through the 75 errors?

leaden ice
#

Most likely a single misplaced bracket is responsible for 70+ of them

cosmic quest
#

lol alright thanks

leaden ice
#

I do see mismatched brackets in the file you shared

surreal phoenix
#

are the URP and HDRP source repos the best resource for learning the ins and outs of the SRP?

leaden ice
#

The package manuals are likely a better resource than reading code

cosmic quest
potent glade
#

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)

potent glade
cosmic rain
#

I think multithreading is not allowed in webgl by default. That being said, default async await in unity runs on the main thread...πŸ€”

potent glade
leaden ice
#

But I'd guess it's from reading multiple files at once?

cosmic rain
potent glade
cosmic rain
potent glade
leaden ice
#

Playerprefs for example can do it

potent glade
potent glade
leaden ice
thin aurora
#

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

potent sleet
#

if coroutines were multithread you couldn't use them in browser

leaden ice
#

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.

thin aurora
#

Either way it's stored in memory and resumed when it reaches whatever the yield wanted

potent glade
thin aurora
leaden ice
thin aurora
#

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 🀷

junior bobcat
potent sleet
leaden ice
#

Unity uses webassembly

potent sleet
#

Oh nice

thin aurora
thin kernel
#

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?

potent sleet
leaden ice
#

Otherwise Unity will never invoke a property for you from the inspector

leaden ice
hexed geode
thin kernel
hexed geode
#

Ye I may just be clueless

dense cloud
#

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

leaden ice
hexed geode
#

What are you confused about?

dense cloud
#

how does the SphereCast take into account the width of the character?

leaden ice
#

By casting a sphere

dense cloud
#

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?

leaden ice
#

Perhaps

#

If you're capsule shaped

#

CapsuleCast exists too

#

You can and should use whatever suits your needs

dense cloud
#

ooo gotcha, thanks man

junior bobcat
#

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?

full bluff
#

!code

tawny elkBOT
#
Posting 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.

full bluff
#
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..

main shuttle
#
foreach (Transform child in transform)
  //these are all the children.
woeful leaf
#

CHILD

rain minnow
#

use a foreach loop on the object transform, use GetChild, or Find. there are tons of ways you can find online . . .

main shuttle
#

Do note that that is an error prone way of doing things, and Gets are slow.

woeful leaf
#

If you (anzee) provide more context we can potentially provide a better solution

crimson flicker
#

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?

main shuttle
#

You can put your debugs in a

#if UNITY_EDITOR
  Debug.Log("In the editor");
#endif
crimson flicker
#

thanks

dense ridge
lusty dragon
#

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?

rain minnow
# lusty dragon Do you guys write variables with a capital letter on the start? I use lower for ...

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

devout solstice
#

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

devout solstice
#

it’s not right

toxic abyss
#

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?

jaunty abyss
#

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; } }

potent glade
#

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??

main shuttle
main shuttle
noble mortar
#

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)
potent glade
thin aurora
#

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

main shuttle
thin aurora
#

Maybe if the dictionary becomes too bloated you can also just remove the lowest weight

full bluff
#

I used a sortedList instead of queue back than but it was kind of slow

potent glade
whole portal
#

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.

sand cedar
#

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.

wide fiber
#
 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? 😦
main shuttle
potent glade
#

can I share the file here @main shuttle

main shuttle
#

What file? Your entire unity project?

#

Or the editor log?

potent glade
#

I htought maybe there's a needed step when opening the project with imac (bcause it was made with a windows)

potent glade
main shuttle
#

Yeah just dump it in one of the code sites

potent glade
#

document exceeds maximum length πŸ’€

#

ok it is on pastofcode.. but how do I share it

#

ok it exceeds the limit there too

hexed pecan
#

Hit save and copypaste the link

potent glade
#

can I just put the file here?

#

finally a website that allows me

main shuttle
#

It seems to cut of too at the end.

potent glade
main shuttle
#

It ends abruptly there for me.

potent glade
#

oh

#

then it didn't share everything

grand rain
#

how do i assign particlesystem force over lifetime in script

grand rain
#

it doesnt say, just read only

thin aurora
#

Is there some Set... method you can use?

#

I.e. SetForceOverLifetime, idk

grand rain
#

i dont think so

thin aurora
#

Then you're not supposed to adjust it

grand rain
#

then i will find some other solution, thanks anyways!

thin aurora
#

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

leaden ice
#

show the full error

#

you would do well to follow the example.

polar marten
grand rain
leaden ice
#

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

polar marten
polar marten
noble mortar
polar marten
#

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

noble mortar
#

If you’re talking to me I do

polar marten
#

well don't delete the comments afterwards lol

sand cedar
#

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.

slim gate
#

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?

prime sinew
slim gate
#

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?

hexed pecan
#

In a lot of cases I prefer the early return, so that the method isn't terribly nested

hexed pecan
slim gate
#

makes most sense i think

pearl swallow
#

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?

stable rivet
# slim gate Are those the same in terms of performance and everything or is there any differ...

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

vapid warren
#

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

polar marten
polar marten
sand cedar
#

I have git installed

polar marten
#

do you use it in this project

sand cedar
#

no

polar marten
#

well

#

unless there are some logs, hard to say what's going on sorry

sand cedar
#

Could be windows overwriting it with its file extension default

stable rivet
#

something in that thread will fix it

mental rover
viscid bane
stable rivet
# mental rover to some extent, though I think dismissing every decision as an optimisation prob...

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

kind wolf
#

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

gray thunder
#

Inheritance

kind wolf
#

is that related to abstract classes

gray thunder
#

Doesn’t have to

mental rover
kind wolf
#

like

gray thunder
#

Google is in a better state to explain it

kind wolf
#

fair enough

gray thunder
#

Its quite easy

kind wolf
#

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

lyric wadi
#

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

gray thunder
#

Thats the point of inheritance yes

kind wolf
#

ah thanks

#

ill look into it

split crest
#

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?

simple egret
#

Yep, it's mentioned in the docs for that method

split crest
#

Oh my God thank you.

#

That was killing me

stable rivet
#

if you had done:

csvdata = Resources.Load<TextAsset>("csvfile.csv");

Debug.Log(csvdata.text);

you would have most likely seen that it's empty

split crest
#

Yes. I just couldn't figure out why it was empty. Thank you so much for your help!

devout solstice
#

Don’t rely on it obviously but it’s really good if you’re having some trouble

tiny delta
#

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?

leaden ice
devout solstice
#

i mean it does help if you know c# so you can see how it works

#

and know if it woul

simple egret
tiny delta
#

Ah, I'll check if I can find which one is missing

queen adder
#

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<>

leaden ice
#

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

queen adder
#

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

leaden ice
queen adder
#

Thanks a lot

tawny elkBOT
#
Posting 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.

#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
upper echo
simple egret
#

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

upper echo
#

please help 😦

simple egret
upper echo
#

im making a level editor and i want to sort the files br recently modified

simple egret
#

You didn't answer my question

upper echo
#

Unix time stamp

simple egret
#

Where is that stored?

upper echo
#

inside the .level file in line 6

simple egret
#

How about using what the file system provides already

#

Like File.GetLastWriteTime

leaden ice
#

or if you just moved/copied files around

upper echo
leaden ice
simple egret
#

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

leaden ice
#

If you use a structured format it's as simple as like theSaveData.modificationDate

tiny delta
simple egret
#

But yeah agreed, JSON or any other structured format would be better here

leaden ice
#

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

leaden ice
#

So you don't have to load the entire save file just to read the modification date

upper echo
#

is gonna be hard to remake its file structure

simple egret
#

So you'll have to do with what you have for now

leaden ice
#

so you don't have magic shit in your code like

#

if (CountLines(AllLevelContents[j]) < 4000 + 15

#

😱

marsh geode
#

lmao

leaden ice
#

and float.Parse(ReadLine(AllLevelContents[i], 6), NumberStyles.Any); 😱

simple egret
#

You can build a data structure that consists of the file path and the timestamp, then use some LINQ to sort it

upper echo
marsh geode
#

?????

simple egret
#

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

verbal heath
#

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

upper echo
#

nvm i fixed it

tiny delta
simple egret
#

Restart Unity if it bothers too much

kind wolf
#

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

leaden ice
kind wolf
#

oh

#

well that kinda sucks is there a way to get a reference to a prefab in the files then?

sterile tendon
#

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?

leaden ice
#

which has references to the other prefab. and instantiate that

sterile tendon
#

or are they the same

leaden ice
#

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

sterile tendon
#

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?

verbal heath
leaden ice
sterile tendon
leaden ice
sterile tendon
#

right now I start main.py with command prompt

#

called from c#

leaden ice
sterile tendon
#

oh wait I didn't know that

sterile tendon
#

oh wow that makes it way easier

leaden ice
#

ofc you'd have to do some multithreading to read this properly

sterile tendon
#

thanks!

simple egret
#

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!

sterile tendon
#

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

verbal heath
#

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

leaden ice
#

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 πŸ˜‰

verbal heath
#

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

leaden ice
verbal heath
#

i have restarted

#

and i have changed versions several times

leaden ice
#

try resetting the window layout?

#

IDK never seen this before

tiny delta
#

What is the result if I try to access a missing point in an array? 0, null, an error, or something else?

leaden ice
#

and what kind of "access" you are doing

#

and what the array consists of

tiny delta
#

As in I have a 1 element long string array and I try to access the third element

leaden ice
#

The C# docs explain this

simple egret
#

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

tiny delta
leaden ice
verbal heath
#

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

tiny delta
#

Oh yeah that would work, wouldn't it

#

I could just add an extra line or two and it should work perfectly. Thanks!

verbal heath
#

!bug

tawny elkBOT
#

πŸͺ² 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

leaden ice
#

is this the same issue you have?

verbal heath
#

oh it is. unlocking the project tab fixed it. thanks a bunch

#

guess i'l try to update to 2023

tiny delta
#

Wait never mind, this shouldn't matter, I was taking the wrong approach from the start.

#

I was overthinking a simple problem

simple egret
tiny delta
#

That makes sense.

simple egret
#

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

tiny delta
#

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)

ancient cloak
#

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?

leaden ice
#

If you used & instead of && it wouldn't work

tiny delta
#

It appears that || works similarly too.

leaden ice
#

yep

tiny delta
#

Oh how do you do the in-line code block?

leaden ice
#

!code

tawny elkBOT
#
Posting 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.

tiny delta
#

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.

somber nacelle
#

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

tiny delta
#

Makes sense, thanks

devout solstice
#

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

somber nacelle
#

make a struct with the two types and have a list of that

cold parrot
devout solstice
#

oh boy

#

I havent messed with structs

cold parrot
devout solstice
#

ok?

cold parrot
#

just do it

devout solstice
#

ill try

cold parrot
#

they wont bite

devout solstice
#

Idk they're looking at me menacingly

cold parrot
#

they are very cuddly if you get to know them

devout solstice
#

oh shit they really wont

#

thats very simple

cold parrot
#

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

devout solstice
#

Now I want to know this analogy but with namespaces

cold parrot
#

namespaces and?

devout solstice
#

Lets see, classes ig

#

Those two are the most similar compared to anything else

cold parrot
#

if structs are dogs and classes are cats then namespaces are houses

devout solstice
#

I see

#

Whats your car? What gets you from place to place

#

Knowing that might actually be useful

potent sleet
#

Car itself is abstraction

#

allow you to interact with all the parts

cold parrot
#

its more about character, not functional analogy

devout solstice
#

Ah aight

cold parrot
#

your car is a properly configured IDE

devout solstice
#

Oh yea fair enough

cold parrot
#

a 747 is kubernetes

devout solstice
#

kubernetes?

potent sleet
#

more like a jet xD

cold parrot
# potent sleet 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

potent sleet
gentle hinge
#

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

devout solstice
#

oh man im stuck

cold parrot
gentle hinge
potent sleet
cold parrot
#

not very accurate, but quick and on demand hitting the general area of the problem

devout solstice
#

Waiiiit is a struct kind of like a tiny class?

cold parrot
#

also lots of collateral damage when used haphazardly

somber nacelle
devout solstice
#

ok

potent sleet
#

structs constructor forces you to assign fields iirc

somber nacelle
#

yeah cannot have a default field initializer in a struct until c# 10 (which unity does not yet use)

devout solstice
#

I am confused af

#

and chat gpt did not help

cold parrot
devout solstice
#

why

cold parrot
#

they give you too many details

devout solstice
#

fair enough

cold parrot
#

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

devout solstice
#

idk how tf to use them for what im trying to do

somber nacelle
#

literally all you need is something like

[System.Serializable]
public struct MyListObject
{
  public SomeObjectType Thing;
  public bool Enabled;
}
devout solstice
#

oh shit

#

I didn't serialize it

cold parrot
devout solstice
#

Lol

cold parrot
#

on the other hand, you wont ever again forget that attribute now

devout solstice
#

Yea

potent sleet
devout solstice
#

oh

cold parrot
# devout solstice Yea

oh, if you want the side-by-side display of the toggle and the reference, you need to make a custom inspector

devout solstice
#

oh

#

yea I dont really want to do that

#

I serialized the struct but it still not showing up

potent sleet
devout solstice
#

wdym

potent sleet
#

eg public MyNewScruct coolio

#

this would show in inspector with all the values

devout solstice
#

oh

potent sleet
devout solstice
#

hey there we go

cold parrot
#

use like this

public class Bar : MonoBehaviour {
  [System.Serializable]
  public struct MyListObject
  {
    public SomeObjectType Thing;
    public bool Enabled;
  }    

  [SerializeField] private List<MyListObject> foo;
}
devout solstice
#

Yea

#

how do I add to the list?

#

Considering the list type needs to be the struct

somber nacelle
#

in the inspector you can press the + button on the list to add a new element

devout solstice
#

in the script

somber nacelle
#

in the code you just call .Add and pass a MyListObject in

devout solstice
#

wat

#

This is what I have

#

ItemType is the struct

somber nacelle
#

you're trying to pass a GameObject not an instance of your struct

devout solstice
#

how do I add the gameobject to the struct, and have it add on validate

somber nacelle
#

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

devout solstice
#

oh

somber nacelle
#

is this your first time using any type in c#?

potent sleet
#

not a struct

devout solstice
#

Item is a list

hexed oak
#

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

somber nacelle
# devout solstice Item is a list

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

devout solstice
#

seems a bit passive aggressive

potent sleet
#

the statement makes sense , if you know how to use a class just change struct to class

devout solstice
#

Aight

potent sleet
devout solstice
#

I kind of want to learn how to use structs though

#

Better then just living off classes instead when I could use structs

potent sleet
#

so add to that

#

you almost had it the first time

devout solstice
#

I tried to but the list type is restrictslot so I cant add the gameobject to it

potent sleet
#

you would need to make a new struct to add to the list tho

devout solstice
#

oh

somber nacelle
devout solstice
#

yea but

somber nacelle
#

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

hexed oak
#

stack v heap too

potent sleet
# devout solstice yea but
   var newItem = new RestrictSlot();
        newItem.Item.Add(ButtonList[i].gameObject);
        ItemType.Add(newItem);```

RestrictSlot needs a GameObject `gameobjectitem ` field
somber nacelle
# hexed oak stack v heap too

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

somber nacelle
devout solstice
#

yea idk

potent sleet
devout solstice
#

I did

#

What do I do with the "var"

potent sleet
#

nothing

#

leave it

devout solstice
#

Where do I put that code?

#

oh

#

I see

potent sleet
#

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

hexed oak
#

That'll work until he finds out to move var newItem = new RestrictSlot(); into the awake loop and cache it

devout solstice
#

what

somber nacelle
#

don't do that

devout solstice
#

ok

somber nacelle
#

you want to add separate instances of the RestrictSlot object into your list

hexed oak
#

Figured he wanted a List<RestrictSlot> slots and he'd have to create it in the awake()

#

ignore me

somber nacelle
#

they already have a serialized list of RestrictedSlot

#

their issue was creating the instances to add to the list

devout solstice
#

Why is it saying Item isn't set to an instance of an object

#

Its to do with the NewRestriction.Item.Count

potent sleet
#

u need to New() a list

devout solstice
#

ah I figured

#

Well shit

somber nacelle
#

why does that even need to be a List?

potent sleet
#

I'm guessing you're doing something with items and inventory, shouldn't use GameObject either

devout solstice
#

because theres multiple gameobjects im trying to add to it

potent sleet
#

make scriptable objects

devout solstice
#

because theres multiple slot

#

slots

somber nacelle
#

yes, but isn't that object supposed to represent one slot?

devout solstice
#

yea

somber nacelle
#

so you want to put multiple gameobjects into one slot?

#

or do you want multiple slots each with their own gameobject?

devout solstice
#

no

#

yea

somber nacelle
#

so don't make that a list, that's why you have a List of the RestrictSlot object

hexed oak
#

to fix the null list you could add a constructor for RestrictSlot that takes in a list and assigns it

somber nacelle
#

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

devout solstice
#

It works

somber nacelle
#

show the current code so we can make sure there wasn't anything else you missed

devout solstice
somber nacelle
#

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

devout solstice
#

is that sarcasm?

potent sleet
#

there was a reason why i used var

somber nacelle
potent sleet
#

maybe I should've explained why I used var in a loop xD

somber nacelle
# devout solstice is that sarcasm?

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

devout solstice
somber nacelle
#

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

pulsar dove
#

[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?

somber nacelle
#

did you commit the gitignore file before the library folder/rest of the project?

pulsar dove
#

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?

somber nacelle
#

yeah

pulsar dove
#

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)

devout solstice
#

How could I get what index one of the slots is in the ItemType list?

vagrant blade
#

IndexOf

devout solstice
#

A bit more complicated then that

somber nacelle
#

in what way

devout solstice
#

its a struct

#

What

somber nacelle
devout solstice
#

Im trying to get the index of the gameobject though

#

like which element its under

#

where it is in the list

somber nacelle
#

there's a few options. the most beginner friendly is just to loop through the list yourself

devout solstice
#

for or foreach?

somber nacelle
#

which one do you think would allow you to get the index?

devout solstice
#

for

#

idk how exactly to do this though

#

I have it going through the list

#

Ah that works

swift falcon
#

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

somber nacelle
#

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

devout solstice
#

IT WORKS

#

I probably did things in the worst way imaginable but it works

swift falcon
#

@somber nacelle thanks for the suggestion. I wrapped it in a conditional check and used combine but it didn't fix it

stable rivet
#

although I wouldn't recommend because it's not the cleanest solution, string fileName = string.Empty at the top would fix

somber nacelle
devout solstice
#

uh boxfriend, it wont let me turn on and off the bool

somber nacelle
#

show what you tried

devout solstice
#

These the two variables

#

Listen boxfriend

#

I still have the other new thing

#

I just did that so I could call to it without having to have a object reference