#archived-code-general

1 messages · Page 41 of 1

dry yoke
#

Realistic with force. I just dont know how to detect if the object is under the water or not.

waxen kayak
#

well easiest method is

#

loop trough all the verticies and get which one is the closest and get it's x axis

#

if it's a shader then get the value on the image that offsets the sea

hexed pecan
#

You can't get the displaced vertices though because they are calculated on the GPU

#

Most likely

waxen kayak
#

oh it's a shader

hexed pecan
#

So you'd have to get a method for wave generation, that you can do exactly the same on the CPU ( C# script) and GPU (shader)

tepid river
#

^

#

replicate the water-movement to get "sealevel" at position xy

#

and then test if you object is so far above below.
guess you could/should approximate by using a simple shape for volume.

waxen kayak
#

can't you just ,,export" the image it uses to offset the water?

hexed pecan
#

Using a texture and scrolling it could work. It would be easy to replicate in C#

tepid river
#

lol the wave-buoyancy thing smells incredibly computationally expensive if you dont heavily approximate.
if you have a large, complex structure it will be some % submerged with a complex wave shape cutting it in half

hexed pecan
#

Could probably get away with a pretty big approximation

#

Lots of room for optimization there for sure

tepid river
#

yeah probably. its not something thats super noticable

hexed pecan
#

Honestly it could be just as simple as sampling a texture 2-3 times, depending on how complex you want it

tepid river
#

hmmmmmmmmmmmm ackually, since we are at it:
add a smoothing shader to get averaged-out waves so its easier to calculate for a whole area?

#

gauss f.e.

hexed pecan
#

Like reading pixels that the GPU/shader generated

tepid river
#

right.. didnt think about reading it lol

hexed pecan
#

This is the reason it would need to be replicated

#

But maybe a rendertexture, Graphics.Blit etc. could help here

tepid river
#

or cheese it. choose wave formula so that its integral is zero => average sealevel is also 0

#

like a sinus or whatever

hexed pecan
#

Yea

tiny delta
#

How would I go about fixing a memory leak? It says "A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details." However, I can't figure out what StackTraces are.

leaden ice
#

but you enable full stack traces from... I believe the console window right click menu

tiny delta
#

I believe I have found out my problem finally - I had accidentally commented out the rebindOperation.Dispose(); which was the cause of the issue

leaden ice
#

this will automatically dispose it when it falls out of scope

tiny delta
#

I think there was some reason for using disposing initially but I can't recall what it was. However, I will try that now that everything seems to be finally working

leaden ice
#

If the operation lives longer than a single scope, then it may be necessary to manually use Dispose

tiny delta
#

How would the using line you sent above work without var?

leaden ice
#

I wrote var because I don't know what the actual type is

#

RebindingOperation?

tiny delta
#

So that would be used on the line where the variable is assigned?

leaden ice
#

where it is declared and assigned, yes

tiny delta
#

The problem is it's declared in a different location from where it is assigned because it is accessed by two functions.

leaden ice
tiny delta
#

Makes sense, I'll check out if by simplifying the code that would mess anything up for the next steps of the inputs

crystal sky
tiny delta
#

At the moment the only thing it is used for accessing a second time is for disabling it

rain minnow
misty jewel
#

Can someone please explain why the following happens?
I have resources as follows

  • Assets/Resources/Entities/Prefabs/resource1.prefab
  • Assets/Resources/Entities/Prefabs/resource2.prefab

When I run
<< Resources.LoadAll("Assets/Resources")

Empty Object[]
✅ Looks normal

<< Resources.LoadAll("Entities")

Object[] length=2
⚠️ should be empty?

<< Resources.LoadAll("Entities/Prefabs")

Empty Object[]
⚠️ Wtf why empty now, but parent directory loads them?

leaden ice
misty jewel
#

Wait wrong code just sec (edited. it is being called like the above)

misty jewel
tepid river
#

hey, im using "inherit velocity" on a particle system. it only seems to work, if the "owning" gameobject of particlesystem and rigidbody are the same.
the system would be a first child though of the gameobject, since its part of a prefab.

is there an easy way to either have it inherit the parents velocity or instead rehome the particle compoinent onto the parent?

waxen kayak
#

Well I just did this

  laser[0].AimReference.LookAt(Target);
         
            laser[0].HorizontalPart.localRotation = Quaternion.Euler(0, laser[0].AimReference.localRotation.eulerAngles.y, 0);

            laser[0].BallPart.localRotation = Quaternion.Euler(laser[0].AimReference.localRotation.eulerAngles.x, 0, 0);
#

it's dumb but works

hexed pecan
tepid river
#

ah you mean i can manually set in a velocity?

hexed pecan
#

Yeah if you need to

#

Not 100% sure if I understood what you want but you can set a custom inherited velocity

#

And update it manually

#

Or you can pick between rigidbody/transform

tepid river
#

yeah you got it right, i think thats what i want.

#

i have a "scene moving" functionality so that the playership stays centered, and now i have to simulate movement for the particles, since the ship is stationary and the scene has to move

#

thanks again 👍

sudden meadow
#

Is this a viable way to copy a list to a new list?

rain minnow
sudden meadow
#

alright so that's fine then to just put it as a list in the parentheses

#

i dont want them as references

rain minnow
#

yes, it's ctor takes an IEnumerable<T> parameter . . .

sudden meadow
#

alright thanks

rain minnow
leaden ice
rain minnow
#

but byte is a value type anyway . . .

#

haha, yeah . . .

sudden meadow
#

true, i just thought the list itself might reference. i'm sure it'll be fine, thanks.

rain minnow
dense vessel
#

Hello,
I'm making an android game using Unity and I'm trying to add a button that would let the user download a file by opening a URL in a browser.
Everything works fine by using Application.OpenURL, the file is downloaded but then the browser stays in the foreground and displays the last page opened...
Is there a way to somehow open it in the background? Or to close it when it has finished downloading the file?
Or any other way to download a file from a URL (if possible without requiring permissions...)?

stuck forum
#

Is it possible to use the base class as a variable type, but access the variable of a specific child script? i thought casting would work e.g

SomeParentScript _child;

(SomeChildScript)_child.SomeValueInChildScript = 5f;

but it did not work sadly

sudden meadow
#

yea thats what i was afraid of 👍

leaden ice
leaden ice
#
((SomeChildScript)_child).SomeValueInChildScript = 5f;```
#

might be more clear / safe to do something like this though:

if (_child is SomeChildScript cs) {
  cs.SomeValue = 5;
}```
stuck forum
leaden ice
stuck forum
#

ohhhh

leaden ice
#

when you do this:
(SomeChildScript)_child.SomeValueInChildScript = 5f;
you're actually doing this:

float f = _child.SomeValueInChildScript = 5f; // << this is already an error
(SomeChildScript)f;```
#

which doesn't make sense really

#

the cleaner way without double parens is this:

SomeChildScript cs = (SomeChildScript)_child;
cs.SomeValueInChildScript = 5f;```
stuck forum
#

i see, that makes sense

leaden ice
#

It's basically just an operator precedence thing

#

the . operator has a higher precedence than the casting

misty jewel
polar marten
polar marten
misty jewel
#

(so I'm loading and caching them)

#

thanks tho

polar marten
#

you can drag and drop

#

everything onto a slot

#

you do not need to use Resources.LoadAll

misty jewel
#

I can't drag and drop at runtime

polar marten
polar marten
misty jewel
#

I know

polar marten
#

create a public GameObject[] prefabs field

#

on a script

misty jewel
#

I need to dynamically load at runtime not at compile time

polar marten
#

resources is still "compile time"

misty jewel
#

Ok

polar marten
#

if you create a resources folder in your player build, it will not be read

#

does that make sense?

misty jewel
#

Yes

polar marten
#

so because you are misunderstanding something about Resources.LoadAll you are using it

#

that is what i am trying to say

#

it doesn't do what you think it does

#

it cannot load anything at runtime. you cannot drag and drop a .prefab file somewhere into a directory for your built player to load.

#

is that your goal?

#

it certainly sounds like it can load things at runtime, but it does not. you might wish it loads things at runtime but it doesn't

#

@misty jewel what is your goal?

misty jewel
#

Now how do I drag and drop 200 items

drifting grail
#

A plugin that shows a link to the method on the wiki would be sick too

#

Gmod LUA has something like this, that's where i'm coming from

#

It was very helpful for as a beginner

eager bay
#

Hey, when I try to set a breakpoint in a package I get "Didn't find the associated module for the breakpoint" in Rider. Specifically I want to modify URP and this is a breakpoint in the URP package that I copied into the Packages folder. Does anyone know what the issue is or where I can start looking for information?

leaden ice
#

it will link to the docs pages

leaden ice
drifting grail
rain minnow
rain minnow
drifting grail
rain minnow
#

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

misty jewel
#

@polar marten so basically I have to make a script for every one of them to manipulate the objects dynamically at runtime
1 script + drag all

pallid coral
eager bay
ebon marten
#

I have a design question related to performance:
Okay, so I have a traffics system and I will be having hundreds of cars travelling around. A given car needs to be aware of cars around it. Would it be better for this car to ask every other car for its position and velocity data, or for the car to ask a TrafficController object that has the position of all cars?

leaden ice
leaden ice
swift falcon
#

Hey i thought i got my code working, but when i try to load a funtion with some arguments i get the error:
Specified key length is not a valid size for this algorithm

#

ìts from this piece of code:

    private static string Decrypt(byte[] soup, string key)
    {
        string outString = "";

        try
        {
            byte[] iv = Encoding.ASCII.GetBytes("1234567890123456");
            byte[] keyBytes = Encoding.ASCII.GetBytes(key);

            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.Key = keyBytes;
                rijndaelManaged.IV = iv;

                outString = DecryptStringFromBytes(soup, rijndaelManaged.Key, rijndaelManaged.IV);
            }
        }
        catch (Exception exeption)
        {
            Debug.LogFormat("Error: {0}", exeption.Message);
        }

        return outString;
    }
#

which i use here:

    private static Dictionary<string, object> GetPrefs()
    {
        string filename = Path.Combine(Application.persistentDataPath, SAVE_FILE);

        byte[] soupBackIn;
        soupBackIn = File.ReadAllBytes(filename);
        string jsonFromFile = Decrypt(soupBackIn, JSON_ENCRYPTED_KEY); //here is a error

        Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
        return prefs;
    }
#

and the funtion i call once on a button press is: BinaryPrefs.SetKey("temp", "hope it works");
the SetKey uses decrypt in it, so it boils down to that

eager bay
# leaden ice Regenerate project files maybe?

I think maybe this was it. I noticed I didn't have "Embedded Packages" checked when generating project files. I guess the IDE was using an old csproj file for the package before it was embedded. Unfortunately I didn't think to keep the old csproj file around to compare with the newly generated one.

charred forum
#

I'm working on a game with enemies that I'd like to have a small UI tied to. The intent is to spawn the enemy in, and then find that position and set the UI to a position slightly below it. I don't need it to update its position after its initial setup, even if the enemy moves it is going to be moving back to its starting spot. I have a second camera that contains all of the UI canvases. The issue I'm running into is when I instantiate the Enemy UI Panel and then try to place it with ScreenToWorldPoint relative to the enemy, it ends up WAY off canvas. I'm not entirely sure what I'm doing wrong, but I'll gladly share any code, screenshots or scene information as needed.

swift falcon
charred forum
#

I need the UI to draw overtop of the environment, and its at an unusual angle because I'm using an orthographic camera for the main scene

rain minnow
charred forum
#

Sure thing! Should I start a thread?

rain minnow
#

are you converting from screen to world or world to screen?

swift falcon
#

i got 3 set up for my game right now, and it works perfectly

rain minnow
charred forum
#

Maybe I can, I haven't really messed with sorting layers, I was just trying to keep my UI separate in world. I suppose in this game it is basically acting as if it was 2d. As for the conversion I am converting from World to Screen in this case. I'm gonna start a thread to drop more detailed information

#

Setting initial UI element position relative to Enemy Object

swift falcon
#

should work

swift falcon
grand elm
#

Hey everyone, I'm trying to do a custom ability system but ran into some trouble. My player character would choose say, weapon type, firing mode, and ammo. Game reads that data from scriptable objects, and now to make that weapon I was thinking of having a CustomWeapon class that changes behaviour depending on said data. Should I look into events and delegates for something like this? custom weapon could subscribe to different events based on player choice (multi shot, full auto, dragon breath ammo) until something changes. Could that work?

polar marten
polar marten
polar marten
#

gradually add complexity when you come up with specific designs

upbeat dust
#

Heyy, so i'm implementing enemy movement.

  1. The enemy will face towards the player
  2. Move forward at a constant speed
if (!velocitySet)
{
      rigid.velocity = transform.forward * 2;
      velocitySet = true;
}```

Problem: i need the velocity **direction to always be updating**. But i want to **set velocity only once**

hewp
somber nacelle
#

rigidbody velocity is in world space so if you want the object to always move forward you will need to keep updating its velocity otherwise it will turn but continue moving in the original direction

upbeat dust
#

i was wandering if you could separetly change the velocity direction via script

somber nacelle
#

rigid.velocity = transform.forward * 2; <- do that

#

literally your issue is that you want to only set velocity once, but you can't only set velocity once if you want the object to keep moving in its forward direction

upbeat dust
#

thank you man

somber nacelle
#

i mean you can increase it, but it's a Vector3 so that would require using += instead of just =

agile zinc
#

I'm using photon pun, both players can create servers fine, but neither can join the other's server.

somber nacelle
severe coral
#

How do I implement a message system into one of my classes similar to how Unity uses messages for MonoBehavior functions like Update(), FixedUpdate(), Awake() and Start()

tiny delta
#

If I want to check if a bool has changed in another script, is it better to try to set up an event in that other script, or should I just add an if statement in Update() which checks the bool?

severe coral
severe coral
leaden ice
#

I don't understand what that has to do with interfaces

severe coral
leaden ice
#

interface members must always be public actually

severe coral
leaden ice
#

I wouldn't recommend it

#

it's tricky to do reflection the way they do and not tank performance

#

you have to cache the MethodInfo etc

severe coral
tiny delta
#

Thanks!

rotund burrow
#

i need to create a collider via script. I'm thinking of scripting a mesh and then just adding collider as component?

leaden ice
vapid bay
#
        if(itemCollect.alive)
        {   

        // Decrease the spawn interval over time
        currentSpawnInterval = startingSpawnInterval - spawnIntervalDecreaseRate * Time.time;
        Debug.Log(currentSpawnInterval);
        
        }
        else
        {
            
            Debug.Log("work?"); // this works
            currentSpawnInterval = startingSpawnInterval; // no change
            Debug.Log(currentSpawnInterval);

        }
#

anyone know why this just goes back and forth and doesnt actually change anything

leaden ice
#

presumably if(itemCollect.alive) is becoming false

vapid bay
#

yeah but when the level resets the original value is still there

leaden ice
#

Time.time doesn't reset when you load a scene

vapid bay
#

o

#

whats my other option

leaden ice
prisma birch
#

Does anyone know why my navmesh would be baking like this? In some places it seems to be getting "pinched" and it's causing my player to fall through the ground. I'm baking using renderers and my geometry wireframe is in the second picture. Can't for the life of me figure out what the cause is.

elfin vessel
#

Is there a smart ledge detection algorithm? As in, if I'm facing a wall, is there an easy way to find out if there is a ledge above it? Mine works but I feel like mine could get buggy quick

elfin vessel
# leaden ice raycasts?

My current strategy is climbing raycasts up the wall until they don’t hit anything, and then casting down from above to see if there’s a suitable spot to climb up on

#

I was just wondering if there was a more elegant and reliable way to do that

cold parrot
elfin vessel
outer plinth
#

Could anyone help me to figure out how I can combine these procedurally generated terrains (marching cubes) together to create a floating island type thing? or tell me if this is even possible?

#

or am I better to just duplicate the mesh and change the values on one mesh?

cold parrot
elfin vessel
elfin vessel
cold parrot
outer plinth
#

@elfin vessel im not entirely sure what you mean, I'm only generating one "cube" at a time, the first pic is when surfaceLevel > size of the cube, and the 2nd is when surfaceLevel = 0

#

so those pictures are of the same cube but with diff surfaceLevel values

elfin vessel
#

Overlap sphere is an idea, use it to flood fill the space (ray casting down wouldn’t always work because there are overhangs and whatnot. Then I could use the flood fill data and process that with an edge detection algorithm. Or maybe I’m thinking about it wrong

elfin vessel
cold parrot
outer plinth
#

yeah, Ideally i would like to make it so that I have a "cube size" and the algorithm would create vertices either side of cubeSize / 2 right, just not sure how I do that

velvet jackal
#

how do i make like a dev chat and buttons like discord in unity 2018.36f1?

potent sleet
velvet jackal
#

is there any guide for it?

void basalt
#

How could a buoyancy solution work? Does the force generally get applied at the corner bounding box positions or something?

lament meadow
#

The yellow raycast is Camera.main.ScreenPointToRay(Input.mousePosition). I wanted the red one to detect if there is an obstacle between the weapon and the enemy. Its top down shooter

I tried with this code:

             if (Physics.Raycast(ray, out var hitInfo, Mathf.Infinity, enemyMask))
             {
                 if (Physics.Linecast(muzzle.transform.position, hitInfo.point))
                 {
                     Debug.Log("blocked");
                 }
             }```
But it doesn't work.
arctic ravine
#

how do you connect one void with another?, rn it doesnt want to do anything with b if its in another void

void basalt
#

it has nothing to do with it being void

#

If your debug.log isn't running inside your trigger, then the trigger isn't being fired

velvet jackal
#

possible?

void basalt
#

Because nobody knows what that means

#

You want to authenticate users over the internet?

velvet jackal
# velvet jackal possible?

explained: a logon screen to a welcome screen with a start button that goes to the menu to a menu with a game menu, developer chat, feedback button, and example name

void basalt
#

That's still too vague

#

is this networked?

#

If so then yeah I mean there's nothing stopping you

#

you'll need to get familiar with sockets and serializing data

potent sleet
#

you can store the info in a file or database as well

#

using a gameengine for this is kinda silly

#

but totally doable

void basalt
#

Pretty sure he's looking for a live chat

#

over the internet

potent sleet
void basalt
#

I don't know why you would store that in a file or database

potent sleet
#

because that's how all apps work

#

with a database

void basalt
#

for live chat?

#

no?

potent sleet
#

wat?

void basalt
#

Why would you do live chat with a database

potent sleet
#

all chat systems have databases

#

why would you not

#

how would you moderate messages

#

etc

void basalt
#

In game servers, clients send data to the host server, and server replicates to clients

#

thats how you moderate it

#

If it were for a website, sure you would probably use a database

#

but not for game servers

potent sleet
#

gameplay server has not much to do with how you deal with your messaging system

#

most of that stuff lives in a database

void basalt
#

gonna disagree

#

obviously it depends on the type of game

potent sleet
#

you can disagree all you want it's pretty known fact

void basalt
#

unless a message is flagged, there's no reason to store it

#

It comes in and goes out

#

Unless you need a history for some reason

quartz folio
potent sleet
void basalt
#

Most people don't care about chat messages that late

#

I play mostly FPS games

#

not card games or whatever

#

so again, it depends

arctic ravine
potent sleet
#

they said a Discord system

#

discord uses db

arctic ravine
void basalt
#

Missed the part where he mentioned discord

#

still dont see it

void basalt
#

Ok

#

probably should have put that in the artwork he drew

severe junco
#

Child start not being called

swift falcon
#

transform.position = new Vector3((startPos + distance) - (Time.time / 2), transform.position.y, transform.position.z); when doing this frustum culling completely breaks and objects spawn in at random times, can be very late or very early, why is this? i'm trying to make clouds move the the left slowly while still having a parallax effect

frosty creek
#

I am trying to create a single prefab for multiple different enemy types in my game and have a scriptable object and i am wondering if i can update the animator components controller
based of the enemyScriptableObject's controller reference

cosmic rain
stark thicket
#

Hi! I'm trying to build an "atlas" function, where the first time you pick up an item it gets added to a dictionary of sorts. I use a raycast to get the object, then it calls an "item pickup" script which is on the items you can pick up, which then gets added to the inventory. This is working well, but when I try to pass the same thing to my "atlas" class, I get "An object reference is required for the non-static field, method, or property 'AtlasSlot.TestFunction(item)".

I understand you can only put static things in other static things, but I'm not really sure where the name of the item got made static in the first place? Any insight would be greatly appreciated! 😄

somber nacelle
#

it looks like you are trying to call your TestFunction method directly from the class rather than from an object reference which is what is causing the error

#

you need a reference to an instance of your AtlasSlot class

rain minnow
stark thicket
#

I really appreciate the help both of you! Yes AtlasSlot is the class name, sorry I'm not exactly sure what that second thing means...

stark thicket
somber nacelle
#

it's not a static method therefore you have to call it on an instance of the object

rain minnow
somber nacelle
#

which means you also need to tell it which instance of the class you want to call the method on

stark thicket
#

sorry I'm not familiar with the term "instance" as it relates to programming. I did find something like that online (as you can see on line 9) and it DID cause that error to disappear but then I was unable to reference game objects on its children

#

since I needed to call this.transform.getcomponentsofchildren blah blah

rain minnow
#

that's how everything works. Time.deltaTime is a static property, therefore you reference Unity's Time class to access it . . .

rain minnow
#

in your TestFunction method you access item2.name where name is a member: field or property, of the Item class. this can only be accessed using an instance of the Item class . . .

stark thicket
#

ok that's given me somewhere to start, I appreciate it. The bug seems to be fixed with the addition of line 9 and the addition of "static" into line 20, but the issue that then arises is that line 23 returns with a null reference.

#

for clarity, the AtlasSlot script is on Atlas Slot 1 and I am trying to get the image component of "shroom"

somber nacelle
#

don't make the method static . . .

stark thicket
#

the bug persists if I remove static from the method

somber nacelle
#

also this should absolutely not be a singleton, get rid of the public static AtlasSlot Instance

somber nacelle
#

you're just brute forcing your way through using the static keyword which is not going to do what you actually want it to

stark thicket
#

Ok maybe I'm not understanding well here because I think I have those item references, in particular on line 10. I reference the image I want to show up in the glossary but that's not what's throwing up the bug. If I need to create some sort of reference to the object being passed in from the ItemPickup script (attached) ON the AtlasSlot script but outside the TestFunc function then that's one thing but would the reference not be created inside TestFunc by the designation of "item2"?

#

And yeah I tried in codebeginner first but they were helping some other people and I didn't want to interupt so I figured general is general

somber nacelle
#

your issue is where you are calling your TestFunction method, not actually in the AtlasSlot class

#

at least it wasn't in that class until you fucked with it

stark thicket
#

OH so I need a reference to the AtlasSlot script IN the ItemPickup script?

somber nacelle
#

yes

#

because as i've already explained, in order to call your non-static TestFunction method you need to reference an instance of the AtlasSlot class

mental reef
#

Hello. I have a code where it stops me from exceeding vertical angles so i cant just look up at the sky as you can see in the video. I know how to make my flashlight follow my mouse but how can i make it so it doesnt exceed a certain angle? I want do be able to go 45 degrees to my left and right and up and down. I tried doing it myself from the code i have from my camera but couldnt

void basalt
#

@mental reefMath.Clamp(myRotationEuler += mouseDelta, min, max);

mental reef
void basalt
#

myRotationEuler is just an accumulator

#

that you can add an Input.GetAxis to

#

so it responds to your mouse

#

So you'll need to apply that euler angle wherever you're doing your mouse rotations

viscid kite
#

when i instantiate an instance of a gameobject does it generate a different guid or inherit the guid of the gameobject it instantiated from?

void basalt
#

The first part identifies the object in the scene

#

the other identifies the actual asset location

#

so the first part will probably change

#

Rolling your own object IDs is much simpler than using GUIDs

mental reef
void basalt
#

This is why we don't copy code from youtube

#

You need to understand how euler angles work before proceeding

#

it's pretty simple

mental reef
void basalt
#

You don't need to lerp your rotations in the update loop

#

show me your cameraSmoothTime variable

mental reef
#

I did try to kind of copy the pivot etc

void basalt
#

What you're doing right now makes 0 sense

#

Let me explain how lerp works

#

You take two numbers. Let's say 5 and 10. Those are the first 2 lerp parameters. The third parameter is a percentage between those two values

#

So 5, 10, 0.5 will give you 7.5

#

It's commonly used with time, when you do it correctly

#

I don't know where you're copying code from, but its definitely not the correct way to be doing things

#

Now I want you go to in the inspector. Click on any game object. Look at the right side of your screen. Find "Rotation" near the top. This is a euler rotation

#

Play with the values and get an understanding of what it does

#

When you want to rotate an object based on mouse movement, we can do rotationXAccumulator += Input.GetAxis("Horizontal")

#

Input.getAxis gives us the difference in mouse movement per frame

#

hence why we're adding it to our accumulator

#

after that you can simply just apply your accumulator on any of the euler axes and there's your rotation

#

In case you're still confused: Remove all the lerp crap from your code

#

that includes slerp

mental reef
void basalt
#

First of all you should probably learn C#

#

and understand what we're doing internally with the values

mental reef
#

Yeah. I am wanting to pursue this at Uni so that would be a wise thing. I am learning as I go but do need to check out Unity's documentation

visual flare
void basalt
#

Here's an example of a common way of using lerp:

float accumulatedTime = 0;
// 5 seconds
float timeToReachValue = 5;

Update loop:

// Add the time in seconds from last frame (accumulating (adding) the values into one)
accumulatedTime += time.deltaTime;

float percentage = accumulatedTime / timeToReachValue;

// Our value will reach 10 in 5 seconds
float currentValue = Lerp(0, 10, percentage);

#

Just in case you were wondering

mental reef
void basalt
#

Telling someone to install bloatware doesn't fix the issue of not understanding how to rotate an object in sync with the mouse

somber nacelle
#

lmao cinemachine is certainly not "bloatware"

visual flare
#

@mental reef find a tuto that walks you through the basics of 3d transforms. you need to be familiar with things like dot product

void basalt
#

It just concerns me that a youtuber is telling people to lerp values in the update loop using a constant alpha

#

to "smooth" it

#

(doesn't smooth anything)

visual flare
#

3rd person camera is all about projecting values in camera space and once you get this the rest will be easier

swift falcon
mental reef
#

I will do. I really appreciate the feedback. Is there also any books/youtubers you recommend? brackleys seems to be good but doesnt make new videos anymore

visual flare
#

yeah forget lerp and smooth until you get the motion right

swift falcon
#

I think it got rid of many redundancies for me

visual flare
#

CM is awesome but won't solve his main issue: he doesn't know the basics of 3d transforms so he'll struggle every steps of the way

swift falcon
#

Ah I see

visual flare
#

and most unity youtubers are no good for the same reason

mental reef
#

I have found some smaller youtubers who will explain the code before the tutorial. I think I'll take a visit to unities documents and watch some videos as you mentioned.

swift falcon
#

I think Code Monkey's 10hr starter tutorial is amazing tbh

#

He shows a ton of basics and good code practices, and explains code very thoroughly

#

I'd highly recommend

visual flare
#

...or catlikecoder. see which one is clearer to you.

mental reef
#

I have been watching code monkey. I will start watching them soon

viscid kite
#

follow up to my guid question. If instantiate a few objects from a prefab, store it into a list and then call findall from the list using the prefab, will it still return all instances of it from the list or no because each instance in the list has its own guid?

ionic adder
viscid kite
#

cause the list will contain a mix of other prefab instances

ionic adder
#

just make a list with the type of object you care about

viscid kite
cosmic rain
#

It will look for that specific object instance(the prefab). If it's not in the list it will not find anything.

viscid kite
#

right

#

but if instantiate from a prefab and store that instance into the list

#

and use that same prefab as the parameter for the list's findall

#

will it be able to grab all the instances stored in the list?

cosmic rain
#

Prefab != Instance of a prefab. From the computer perspective "they're 2 completely different objects, wtf are you talking about"

austere jasper
#

Not if you compare with the prefab (asset) directly.
If you do prefab (asset) == prefab (instance), it will be FALSE

viscid kite
#

that's what i wanted to make sure

ionic adder
#

this seems like a super roundabout way to access the instances of a prefab. why can't you keep them in a distinct list and skip the findall usage

cosmic rain
#

Or a dictionary of lists where prefabs are the keys.

viscid kite
#

i guess i'll specify the problem and you can tell me if that method can still work or if i need to try something else.

#

cause i was pondering on the different bins

#

so basically i have three telegraph variants for enemy attacks

#

most attacks will use one, but other attacks may use a mix of other telegraphs variants

#

and so what i wanted to do was have a parent object

#

and either reuse or create a new instance of a certain telegraph instance

#

the latter done up until the difference is 0

#

the reason i wanted to opt for using them all in the same bin was to line them up with the timer array (float)

#

so that on the same index of the timer array each telegraph will complete on their respective index

cosmic rain
#

Telegraph?🤔

viscid kite
#

basically a warning area of an attack

austere jasper
#

No, he means, attack telegraphs, like a bright flash on the enemy weapon when they start a wind up attack, or an AOE indicator on the ground

viscid kite
#

in this case the latter

cosmic rain
#

Oh, ok

viscid kite
#

i guess i can technically run them into different bins but i worry about wasting too much memory.

cosmic rain
#

The first time I heard that word I'm that context, but ok.😅

vestal crest
#

hi, i was wondering what is startTangent and endTangent? i was trying to use handles.drawbezier and i wonder how to calculate these 2 parameters

austere jasper
#

To me it seems like you want a pooling system eye sea, is that correct?

viscid kite
#

yes

cosmic rain
viscid kite
#

so one array for circle telegraphs, one array for a fan telegraph

austere jasper
#

bin == pools

viscid kite
#

ye

#

i guess that means kwewe (queue) system?

austere jasper
#

or a stack.

#

Either way, what you want is a pooling system, and you can use a dictionary for it, with the parent prefab as the key, and a List of the instances as the 'availableInstances'

viscid kite
#

right an object pool

#

i guess from there it becomes a matter of lining up the timings

#

timing basically being

austere jasper
#

I'm not sure why lining up the timings is the issue

viscid kite
#

basically i want each used instance of the telegraph to line up with a float array indicating how long until the attack hits for each telegraph

#

i guess should i just pop/pull into a list?

#

until it lines up to the length of the timing array?

austere jasper
#

That behaviour shouldn't matter for your pooling system.

Your telegraph attack should be told 'you will last for X seceonds', and it performs its actions, and once the time is up, it disappears and returns itself to the pool

viscid kite
#

got it

#

i guess for this i'll have three float arrays for the timings of each category in the pool so that when i pop it out of their category stack i'll line up the count and load the telegraphs with their timer.

#

basically pulled from circle telegraph pool and on index 0 of timingcircle (the you will last x seconds array for circle telegraphs), load that popped circle telegraph with the duration of timingcircle.

cosmic rain
#

Why does the pooling system needs to know anything about timings or anything else related to attacks??

viscid kite
#

not the pool system itself but once i pull out of the pool.

cosmic rain
#

You should have an attack object that should handle whatever logic is relevant to the attack. Then it just gets your polled object from the pool, uses it as needed, and returns it back when done.

viscid kite
#

i still need to load the telegraph with how long the telegraph will last

austere jasper
#

you don't need to load it with a time

#

you play it with a time

cosmic rain
viscid kite
#

not like loading screen, basically, each telegraph has a telegraph script that upon calling that function will activate a coroutine that lasts for the time loaded in.

Once that coroutine ends, the last few lines of the coroutine will basically do the enemy logic before being put back into the pool.

#

that's how i'm picturing it

austere jasper
#

It seems like you're coupling the telegraph with the execution logic

viscid kite
#

yeah because when the telegraph appears, a bar appear belows the telegraph that fills up and once it fills to 100% (or scale 1), then the logic activates.

#

i presume there's a much better way of doing this.

cosmic rain
viscid kite
cosmic rain
viscid kite
#

basically telegraph[0] will be given 1.5 seconds, telegraph[1] will be given 2.0 seconds

viscid kite
#

basically for example one boss slamming their sword on the ground with a main telegraph on the sword slam and 4 circle telegraphs on the corners
(so the main telegraph that will rely on animation time) and then 0.5 seconds later the 4 circle telegraphs will activate an explosion.

austere jasper
#

That should be handled by the boss's attack behaviour

#

the telegraphs should not have to worry about when they will be played

#

The ONLY thing the telegraphs should be concerned about is:

#

At a bit of a higher level
'WHERE am I supposed to be positioned.'
'HOW long am I going to stay on screen?'
'HOW long has it been since I've been on screen'
'Given how long has it been, and how long I am still going to stay, what should my artwork look like? (fill the inner circle/edges/opacity whatever'

cosmic rain
#

I'm still curious where does that "telegraph" word comes from though? Can't find any mention on the internet, but there are 2 out of 3 people here that know what it is, so it must be something common..?

viscid kite
#

i mean for what i have it's been doing that since the boss behavior will do overlap collider on the telegraphs when each telegraph is about to expire.

viscid kite
austere jasper
austere jasper
#

Have you seen the sentence 'wind up animation'?

cosmic rain
viscid kite
#

it comes in many flavors

#

wind up animation, visual cue, telegraph

cosmic rain
#

Aight. Guess I've been living in a cave

viscid kite
cosmic rain
#

So, it's some kind of subtle indication for a player of an upcoming attack

austere jasper
viscid kite
#

in my case a mix of both

#

ah

#

ok so essentially

#

leave the timings of the attack and when they do the scan to the boss not the individual telegraphs.

#

the telegraphs will appear and once certain moments occur (like an attack animation doing the damage frame), on boss side scan that area then remove the telegraph

austere jasper
#

the boss itself doesn't have to remove the telegraph.

#

The telegraph can be responsible for removing itself

viscid kite
#

some external manager i presume?

#

oh ok

#

so same coroutine behavior

#

but when coroutine end, then return to pool

austere jasper
#

mhm

#

the only reason you'd really have for the boss to remove a telegraph is if for example the boss is winding up the attack, but the boss gets stunned

viscid kite
#

right which i have a script for canceling telegraphs in the event they get stunned

austere jasper
#

then the BOSS should disable the telegraphs it has spawned

viscid kite
#

i think i ran with a queue system before

austere jasper
#

I am not sure however, in which version of unity it was introduced, so if you are using an older version, it may not be available

viscid kite
#

but got it

#

2021.3

#

so i'm pretty sure it has it

austere jasper
#

Mhm, whichever system works for you

worldly hull
#

somehow any version that is later than 2021.3.16f1 crashes

#

3.16-3.18f1

#

2022 is fine tho, but thats in beta

brittle cobalt
#

HI! Any idea why I get that error message? I still can't figure out what is causing the issue. Here's the code im using for that part (if need the whole script lmk)

public Transform firePoint;
private GameObject currTarget;
private float currTargetAngle;
...
Vector2 lookTarget = currTarget.transform.position - transform.position;
currTargetAngle = Mathf.Atan2(lookTarget.y, lookTarget.x) * Mathf.Rad2Deg;
firePoint.rotation = Quaternion.Euler(0, 0, currTargetAngle);

Error appears to be in line Vector 2 lookTarget = currTarget.transform.position - transform.position;

somber nacelle
#

currTarget is null. where do you assign it?

brittle cobalt
somber nacelle
# brittle cobalt

and are you null checking currTarget before you execute the code where your error is happening?

brittle cobalt
somber nacelle
#

while(i >= tables_txt.Count)
i'm gonna go ahead and point this out again

#

think about that condition for a second. then consider the fact that you increase i within the loop but you don't seem to do anything at all to the tables_txt List

#

right but you're still not thinking about that condition

#

what is the value of tables_txt.Count when you want to start that loop?

#

and is 1 greater than or equal to 12?

#

yes, your condition is wrong so it never enters the loop. and even if it did enter the loop it would be an infinite loop

#

wdym "its just a typo". is this or is this not the code you are using?

#

because if it is then your code inside the loop never executes

#

and if it is not the code you are using then you need to share your actual code'

#

or use a for loop instead of a while loop

#

before we begin troubleshooting that line, just to be clear this is for code that only runs in the editor, right?

#

ah wait, i misunderstood you kept saying "assetdatabase" and i assumed it was referrng to the editor class AssetDatabase but it's for the LocalizedAssetDatabase from the localization package. one sec while i go ahead and look that up real quick

#

could you be more specific about what you mean by "it doesn't work"? do you receive an error? is it just returning null? is something else happening?

#

LocalizedValue is a string

river cove
#

Can anyone help me with a bug im having if you know anything for a jam: I have an inventory system that on collected input takes in item data and assigns it across classes to initialise items in the inventory. For some reason on one specific line i am getting a null error that is my sprite image of the class being set to the inputted item that was put as a parameter.

#

ive went through about everything and it should be fine theres even a tutorial on most of the systems I dont know why this null error is here

somber nacelle
#

did you drag an Image component into the inspector for the image variable?

river cove
#

ya

somber nacelle
#

and you are certain that newItem is not null?

river cove
#

theres no way it could be after collecting an item I just cant see how through the 3 methods or so

somber nacelle
#

add these two lines to the beginning of that method, you'll get an error telling you which one of the two is null (since those are the only objects on that line that would throw a NRE) and you can then click the error and it will highlight the gameObject that it is null on
Debug.Assert(image != null, "image is null", gameObject);
Debug.Assert(newItem != null, "newItem is null", gameObject);

river cove
#

its not rly giving me anything

#

all its says is null reference exception in that

somber nacelle
#

that's not related to your code, unless you're writing editor code

#

it's also not related at all to the method you showed

river cove
#

oh here it is thats just another null

somber nacelle
#

what is line 20 of InventoryItem

river cove
#

its been this

somber nacelle
#

i also see the assert printed, but of course it looks like you've changed the message

#

click the True message and see where that originated from

somber nacelle
#

ah wait, i forgot the quotes so that's on me actually

#

which line did it come from though

river cove
#

Inventory item 20

#

the sprite one again

somber nacelle
#

the assert error message, what line did that come from

#

or just go back to the message and copy what they are now and try it again

river cove
#

k

somber nacelle
#

well there you go, newItem is null

zenith atlas
river cove
#

theres just no way tho 😵‍💫

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.

somber nacelle
#

what calls AddItem

zenith atlas
#

How deep it is 🙂

somber nacelle
#

christ this is such a long chain of methods passing null around

river cove
#

i know

#

add item is called by the collector script and each item script

zenith atlas
#

code

river cove
#

an item

#

collector

zenith atlas
#

And who calls Initialize ?

river cove
#

nothing?

somber nacelle
#

well there's your issue then

river cove
#

alright so do i put initialize in the start method

zenith atlas
#

No, better look carefully to the tutorial, idk

river cove
#

alright the collector script was from a different one a while ago so that y i dont know

#

ill find it

zenith atlas
#

Send us the link to the tutorial

river cove
#

the inv or collector

#

the inv is a great tutorial

river cove
#

idk i cant rly find it seems to just be a mash of videos and personal attempts

#

going to try a new collection system

#

if this dont work i def cant post anything for the jam

somber nacelle
river cove
#

isnt it checking if i can add to the inventory and then calling the collect method on the collectible in the last line

#

i dont understand

somber nacelle
#

your check to see if you can add an item is what is causing your error in the first place

river cove
#

are you sure?

somber nacelle
#

yes because that's where you pass your null item variable to AddItem

#

remove the entire bool canAdd line and the condition to call collectible.Collect()

river cove
#

i just did and you are right

#

i still have a null but the items are working correctly

somber nacelle
#

is the NRE in the same place as before? or is it somewhere else now?

river cove
#

its this weird one that gives like no info

somber nacelle
#

yeah that's a unity error. do you have a custom inspector or some asset that includes editor code? if not just restart the editor and it should go away for a little while

river cove
#

yeah it doesnt pose a significant problem besides just being random i dont have anything special or assets that arent my own

#

thank you so much actually bruh i dont know why theres no information considering that guys tutorial was pretty big

somber nacelle
#

well if that line that was passing your null item didn't come from the tutorial then i don't see why it would have been covered in the tutorial 🤔

river cove
#

it did so

#

there was just no comments nothing i like quadruple checked

#

it works now its just i have to find a way to check for those additems parameters before adding again without an error

#

but the state its in now compared to before is 100 times better

late grotto
#

Hey ppl, got a quick question.

urban marsh
#

hey guys !
I have a collider related question :
In my 2D game, I have a tilemap to handle the background graphics and colliders for the general player and enemy movement. For example, I have pools of lava that prevent player/enemy movement, with the tilemap composite collider to form a mega collider and prevent things from going into the lava.
The thing is, if I instantiate an enemy IN the lava pool (inside the collider). it does spawn inside the lava pool, and is stuck inside the lava pool's collider.
Is there a way to have things be moved outside the composite collider when spawning ?

merry cape
#

Hello everyone,
I am adding a save/load system to my game. My game has also 8 scenes in total. So I need a way of persisting player data between scenes. I researched the possibilities of solving these requirements and now I am deciding between two ways of implementing this.

  1. Creating a scriptable object to persist data in between scenes through the whole runtime of game. Then serialize this scriptable object into json file on game quit. On the next run I would deserialize a json file and load data back to the scriptable object.
  2. Do it without scriptable object! On game load/save just serialize/deserialize all the required game objects and data with use of json file the same way as in the first option. Use this logic also on transitions to another scene. Save all data to a json file when exiting the main area and then load it when loading the next level.

Which option is better and why? Or is there another better option that I missed?

swift falcon
opal lance
#

Hello there, I'm creating a 2D top down shooter game using Unity for practice, and even though this is my first time, I've been fixing problems left and right by myself, until now. In my game, I've implemented a game mechanic where if you press 'E', your character turns into a cardboard box, and the enemy cannot detect you if you're in the cardboard box (like in Metal Gear). Functionality-wise, it works perfectly. The enemy has a radius where if the player is within the radius, it'll approach the player. But unfortunately, instead of the player turning into a cardboard box, the player just disappears.

I've tried tinkering with my scripts, and I've tried checking the cardboard box gameObject to see if I'm missing components but afaik I see no problems. although I might be wrong, I'm stuck in this problem and I really want to fix this before addding more into my game. Can someone please help? How do I make the cardboard box appear?

marble panther
#

I have a program inside my code that makes a grid of x,y coordinates and puts them in a list. I'm trying to return them to see how exactly they're ordered, but all i get is this "System.Int32" thing

#

The gridInstantiate is called during the Start function elsewhere in the code. Is it just a matter of where the line is placed to get results?

sleek bough
# marble panther

It prints out what you asked it to print out, your list of tuples (the object). If you want to print actual values you should print them instead inside the loop.
Also you need to setup your !IDE properly.

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

marble panther
#

what is IDE?

sleek bough
#

Visual Studio is an integrated development environment

marble panther
#

how do i set it up?

sleek bough
marble panther
#

ah

cedar pivot
#

all of my prefabs has same components ()

sleek bough
#

@cedar pivot Don't cross-post. And this is not a code issue

velvet jackal
#

Vivox did not work there is not a samples dir in the windows 10 SDK

worldly latch
#

This is most likely basic maths but I'm not exactly good at maths... Problem: Want the vector2 "inputs" (equal to Input.GetAxisRaw("Horizontal"), etc...) to have less strength when the float "momentum" gets bigger. Momentum is clamped between 1 and 1.15, I thought a lerp would work but I can't figure out how I'd use the lerp

leaden ice
#

Or I guess you're wanting a remapping function

worldly latch
#

Well the inputs should be lower strength the higher momentum is, if momentum is 1.075 then inputs should only be able to reach -0.5 or 0.5

leaden ice
#

it's a remapping function

worldly latch
#

Now this is the basic maths I've been looking for lol

#

thank you!

#

Couldn't figure out what to search up online for the question but this is what I was looking for

mellow rain
#

return Physics2D.BoxCast(bCol.bounds.center, bCol.bounds.size, 0, Vector2.something, 0.1f, wallLayer);
I'm using this code to identify if my player is touching a wall, but I'm struggling with Vector2.something. If I use 'left', wall collisions are only detected on the left side, right makes them only detected on the right, down makes them not work at all and same with up. Is there somehting that exists like Vector2.centre that I can use instead of up/down/left/right, or will I have to calll this BoxCast twice, once on the left and again on the right?

wintry crescent
#

wait, no, I misunderstood what BoxCast does

wintry crescent
mellow rain
swift falcon
#

Hey i get a missing reference exeption

#

but i give the parameters in the funtion

#

wait i'll upload the snippet

#
    public static void SetKey(string key, object value)
    {
        Dictionary<string, object> prefs = GetPrefs();
        prefs.Add(key, value); // line 36
        SetPrefs(prefs);
    }
    public static object GetKey(string key)
    {
        Dictionary<string, object> prefs = GetPrefs();
        if(HasKey(key))
        {
            return prefs[key];
        }
        return null;
    }
#

this is the funtion

#
        if(Input.GetKeyDown(KeyCode.M))
        {
            BinaryPrefs.SetKey("test", "yeah this is still a test");
        }
        if (Input.GetKeyDown(KeyCode.N))
        {
            Debug.Log(BinaryPrefs.GetKey("test"));
        }

this is where i call it

#

these are the errors

#

i do give the right parameters so i really don't know what's going on

mellow sigil
#

Which lines are 36 and 69?

unkempt sail
#

what does GetPrefs() do?

swift falcon
mellow sigil
#

It's returning null so you have to show it

swift falcon
#

Setprefs does the opposite

unkempt sail
#

well it seems that GetPrefs returns a null ref

#

so when you call the function, it spits a Null Ref exception

swift falcon
#

ohh

#

i thought the parameters were wrong

unkempt sail
#

try a try statement to verify

swift falcon
#

i know what i can do...

#

one sec i'll try

#

i check if the json from the data is not null

#

then turn the json into a dictionary

#

it the text is null, i spit out a new dictionary so there is no error

#

testing it rn

#

nope

swift falcon
# unkempt sail what does `GetPrefs()` do?
    private static Dictionary<string, object> GetPrefs()
    {
        string filePath = Path.Combine(Application.persistentDataPath, SAVE_FILE);

        if(!File.Exists(filePath))
        {
            File.Open(filePath, FileMode.Create);
            File.Create(filePath);
        }

        File.OpenRead(filePath);
        string data = File.ReadAllText(filePath);

        string jsonFromFile = ReverseCrypt(data, JSON_ENCRYPTED_KEY);

        if(jsonFromFile != null)
        {
            Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
            return prefs;
        }
        else
        {
            return new();
        }
    }

this is the code

unkempt sail
#

check if it returns a valid object

#

maybe drop a break point

swift falcon
#

and how can i do that?

unkempt sail
#

what IDE do you use

wintry crescent
unkempt sail
#

new C# 11

swift falcon
unkempt sail
#

that's alright

#

at the top look for the "Attach Debugger" button

swift falcon
unkempt sail
#

and next to the line click to add a break point

swift falcon
#

funtion break point?

unkempt sail
#

if you run unity, and it has been attached to VS, it should freeze and send you to the point where the program broke

swift falcon
#

okk

unkempt sail
swift falcon
#

im confused af 😭

wintry crescent
unkempt sail
#

no

#

put the break point your self

swift falcon
#

toggle break point?

unkempt sail
#

the red point

swift falcon
#

ohh ok

#

like this?

#

when i get the error nothing happens

wintry crescent
unkempt sail
#

not in my experience

swift falcon
#

welp

#

but i do check if it's null???

        if(jsonFromFile != null)
        {
            Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
            Debug.Log(prefs);
            return prefs;
        }
        else
        {
            return new();
        }
mellow sigil
#

The same way you check if jsonFromFile is null

swift falcon
#

?

swift falcon
mellow sigil
#

Yes, and you can do the same to prefs

swift falcon
#

this is everything

swift falcon
mellow sigil
#

Well, what do you want to happen in that case?

swift falcon
#

alrighty

#

1 sec

#
        if(jsonFromFile != null)
        {
            Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
            if(prefs == null)
            {
                return new();
            }
            return prefs;
        }
        else
        {
            return new();
        }
#

well it works

#

but now i get an io exception for opening files 😃 🔫

mellow sigil
#

That's a bit convoluted but 👍

swift falcon
swift falcon
mellow sigil
#

I mean you could just do

if(jsonFromFile != null)
{
    Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
    if(prefs != null)
    {
        return prefs;
    }
}
            
return new();
swift falcon
#
return (prefs == null ? new() : prefs);
swift falcon
swift falcon
wintry crescent
wintry crescent
swift falcon
#

thanks for all the help guys!! <3

mellow rain
#

public bool isGrounded()
{
return Physics2D.BoxCast(bCol.bounds.center, bCol.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
}
I have this grounded check I'm using in my game and I've noticed that under certain circumstances it doesn't run. Is there anyway I can force the code to run this?

wintry crescent
mellow rain
#

It won't update

#

I'll be off the ground and it'll return true and I'm pretty sure it's becuase of other method that's going on

wintry crescent
#

add a Debug.Log(bCol.bounds.center) before the return
and a debug.log(playerPosition) or something as well
and see if they change in the same way

mellow rain
#

It only shows the Debug.Log message whenever I jump or land from jumping. But when I'm running, it displays an updated position constantly

thin aurora
#

Code always runs when it has to run

#

So you should verify how isGrounded is supposed to be called, and check if every predicate leading up to it works.

mellow rain
hexed pecan
#

I mean that depends on how you coded it

#

Could share the script?

mellow rain
autumn cipher
#

I hate using LateUpdate but I have to

  private void Update()
        if (RecoilTimeStamp < 1f)
        {
            RecoilTimeStamp += Time.deltaTime;
        }
  private void LateUpdate()
    {
        if (RecoilTimeStamp < 1f)
        {
            if (!player.CurrentWeapon.isBoltActionOrPumpAction)
            {
                Debug.Log("RecoilTimeStamp" + RecoilTimeStamp);
                Debug.Log("lerping value " + Mathf.Clamp01(20f * (1f - RecoilTimeStamp)));
                player.CurrentWeapon.SlideTR.localPosition = Vector3.Lerp(targetSlidePos, defaultSlidePos, 20f * (1f - RecoilTimeStamp));
            }
        }
    }```
weird bug I guess, the 2nd debug and the lerping happens AFTER RecoilTimeStamp reaches 1 when the opposite should have happened
#

something about Mathf.Clamp01() messes it up

#

one more thing, when I don't multiply those by 20f they just as intended but I don't know how to speed up the lerping any other way

leaden ice
autumn cipher
leaden ice
compact spindle
#

I've been trying to call my animation transition function via animation events and every event trigger has been throwing errors and not working correctly

autumn cipher
leaden ice
#

show the console window

#

also show the rest of the code

wintry crescent
#

to speed it up

autumn cipher
leaden ice
#

not sure what you mean

autumn cipher
leaden ice
#

it is doing that

#

I'm trying to figure out why you're doing the Lerp in reverse
and then doing 1 -

leaden ice
#

Why not just Lerp... forwards

#

Also you're only doing the Clamp01 inside the log statement, not in the actual Lerp call

#

not that it matters

#

since you're limiting it with the if statement

autumn cipher
autumn cipher
open cosmos
#

hey guys how do I get my character to rotate towards direction of movement? Here's my code for reference;
https://paste.ofcode.org/Drit5uywCXaj55D8M5EmJY

For some reason when I press "left" the character rotates left then moves "left" of wherever that character rotated instead of moving forward in the direction it's facing. Same with the other directions I'm pressing. This code is kicking my ass haha.

compact spindle
#

The Animation Transition function gets called, but throws an exception and doesn't follow through with the event function:

#

It's frustrating because this is happening across all times I call the animation transition event function in Unity's animation ui

lucid valley
#

either use some logs to find out which or attach a debugger

compact spindle
#

will do, thanks for the help!

covert turret
#

I'm getting some inconsistent behaviour working with floats:

#

Can anyone possibly explain?

lucid valley
covert turret
#

oh crap

lucid valley
#

use Mathf.Approximately()

covert turret
#

what do?

compact spindle
covert turret
#

aight bet

#

thanks man

cloud smelt
#

Is anyone able to give some advice on setting up a game grid? I currently have a grid consisting of game objects and fire a raycast from the player to the grid to allow them to interact and plant crops. Is this a legitimate way of doing this or is this a big mistake?

covert turret
#

funny you say that, Im working on grid placement right now. My option was to either do what you just said, additionally rounding it. Otherwise I was going to use an array and just use the indices for the coordinates

#

Working great so far for me

wintry crescent
covert turret
#

I'm using a combination of both to validate that the grid is correct and potentially store information in the array

wintry crescent
#

a raycast feels too risky

cloud smelt
#

Its just I had someone with a lot more experience tell me it was an awful way to do it but didnt offer any solutions...

lucid valley
#

i wouldnt say its awful

#

just theres alternatives since you are 2d

covert turret
#

Sure its not as best of a solution as others are.. but if you absolutely need to do raycasts, you can make it work

wintry crescent
#

raycasting would be a very nice idea, if your player could move by ignoring the grid cells
but if the player can only jump from 1 cell to another, I don't think it's a particularly good solution
although it could work

covert turret
#

you will just need to do some calculations to ensure it actually gets the grid correctly

cloud smelt
#

Oh my player can indeed move by ignoring the grid cells, the cells are only needed for planting and building paths.

wintry crescent
cloud smelt
#

I guess it wouldnt be the best way if I wanted tiles to know what is happening on the tiles next to them, maybe I also need to go the hybrid route

covert turret
#

why not? You can step through a 2D array like coordinates

wintry crescent
lucid valley
#

gameobjects are not efficient, they have overhead

#

better to just store tile data in an array on a singleton so you can access it anywhere

wintry crescent
#

but yea I also had an array

#

with everything

cloud smelt
#

Back to the drawing board then haha

covert turret
#

with my hybrid approach I round the raycast hit, cast that to an int, voila array index

cloud smelt
#

So just use a standard tilemap with all tiles in an array, I can then use mouse or player position to get a tile and do all my crop planting from the grid manager.

#

@wintry crescent You dont on the off chance have any example videos or tutorials of the 2D array setup you mentioned for the tilemap?

jade yarrow
#

anyone able to give me some help making a unity loadout system for my multiplayer fps thats running on photon

wintry crescent
mellow rain
wintry crescent
dapper schooner
#

does anyone know of any git resources for UI glow? If can be a blur or something faked. I am just trying to have a button glow on hover. Without post processing.

wintry crescent
hexed pecan
mellow rain
#

isGrounded doesn't seem to be updating properly during Sprint and dashJump

hexed pecan
#

Also you could make these logs a bit more readable:

print(onWall());```
Like this:
```cs
print("On wall: " + onWall());```
#

(Or this, if string interpolation accepts methods, i forgot)

print($"On wall: {onWall()}");```
mellow rain
#

Ah, sorry

hexed pecan
#

I mean more like readable for you

#

So you know whats going on in the console

mellow rain
#

Yeah

#

I am a little confused on exactly where the problem is with which variable a method

hexed pecan
#

I would store the grounded state in a bool, and only calculate it once per frame.

#

Currently you are doing an expensive boxcast every time you call isGrounded()

mellow rain
#

How often is isGrounded called? I got it from a yt tutorial but they never really said

hexed pecan
#

Something like

bool isGrounded;
// And change the isGrounded() method to
bool GroundCheck()
{
  isGrounded = Physics.BoxCast(...)
}```
hexed pecan
#

Which looks to be like 10+ different places in that script

mellow rain
#

Really?

mellow rain
mellow rain
dapper schooner
hexed pecan
wintry crescent
dapper schooner
mellow rain
#

So, for a potential fix, at key points in the code, I call all neccessary methods (isGrounded, onWall etc.) and then calculate to see what movements the player can make?

wintry crescent
#

nor the user of the headset ;P

hexed pecan
#

I suggest calling GroundCheck in the start of FixedUpdate. This way you update the isGrounded bool once every physics frame, instead of calculating it again every time you want to know the value

hexed pecan
#

Well not directly a fix, but it could make it a bit more readable

#

And easier for you to debug

mellow rain
#

What is the difference between update and fixed update?

hexed pecan
#

Update runs "as fast as it can", its basically the render loop. It's execution rate depends on your FPS

#

FixedUpdate runs at a fixed interval (default 50 times a second) and its mainly used for physics stuff

#

As a rule of thumb, visual stuff and input -> Update. Physics stuff -> FixedUpdate.

mellow rain
#

Nice. I'll give that a try and see what changes, while also cleaning up anything else

#

Although, apologies in general for the poor organisation of the code at times, this is a school project and I only need to show parts of the code, so the organisation goes unseen. Also, it's due 2nd March with documentation, so this'll be a bit of a rush job. Definately will come back and continue working on it when I'm done though

#

With that being said, thanks for the constant help 👍

swift falcon
#

Hey i got a question again

#

dataPath and persistentDataPath are both not writable

#

i can read from them

#

but not write

wintry crescent
lucid valley
#

seems rather obvious they would be read only

swift falcon
#

and i want to write to "Application.persistentDataPath + player.feverdream"

#

and read of course

#

but it won't let me

lucid valley
#
  1. use Path.Combine(), that will add the necessary \ between the two paths
swift falcon
#

string filePath = Path.Combine(Application.dataPath, SAVE_FILE); still gives the same error

lucid valley
#

have you added the file type?

#

like .txt to it as well?

swift falcon
#

yeah

lucid valley
#

humm, well sharing violation seems like you are reading and writing at the same time in two streams?

swift falcon
#
private static readonly string SAVE_FILE = "player.txt";
lucid valley
#

show the code where you read it and write it

swift falcon
#
    public static void SetKey(string key, object value)
    {
        Dictionary<string, object> prefs = GetPrefs();
        prefs.Add(key, value);
        SetPrefs(prefs);
    }
#

GetPrefs and SetPrefs both have a file read or write in them

lucid valley
#

show them both

swift falcon
#
    private static void SetPrefs(Dictionary<string, object> prefs)
    {
        string json = JsonConvert.SerializeObject(prefs);

        string data = ReverseCrypt(json, JSON_ENCRYPTED_KEY);

        string filePath = Path.Combine(Application.persistentDataPath, SAVE_FILE);
        File.OpenWrite(filePath);
        File.WriteAllText(filePath, data);
    }
    private static Dictionary<string, object> GetPrefs()
    {
        string filePath = Path.Combine(Application.persistentDataPath, SAVE_FILE);

        if(!File.Exists(filePath))
        {
            File.Open(filePath, FileMode.Create);
            File.Create(filePath);
        }

        File.OpenRead(filePath);
        string data = File.ReadAllText(filePath);

        string jsonFromFile = ReverseCrypt(data, JSON_ENCRYPTED_KEY);

        if(jsonFromFile != null)
        {
            Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
            return prefs == null ? new() : prefs;
        }
        else
        {
            return new();
        }
    }
#

ReverseCrypt just makes the json text encrpyted / decrypted

lucid valley
#
using (FileStream fs = File.OpenWrite(filePath))
{
    fs.WriteAllText(filePath, data);
}
#

try using it like this for both

swift falcon
#

alright

#

filestream does not contain WriteallText

#

it does have Write but that is for a byte[]

lucid valley
merry sequoia
#

How can i access this percentage from my code, so i can for example print it in a debug log

swift falcon
#

FileStream does not contain a definition for "WriteAllText" same with "ReadAllText"

lucid valley
swift falcon
#

hmm ok

#

ill use that

#

and for reading/

lucid valley
#

humm, yeah i was just thinking of how to read

#

humm, actually is there just WriteLine()?

#

as i think the reader can then just do ReadLine(), instead of trying to convert

swift falcon
#

oh btw file stream wants a offset and count??

#

i just have the file path and the bytes

swift falcon
lucid valley
swift falcon
#

WriteLine does not exist

#

Oh i can just use Write

#

since i give the filepath in the using statement

lucid valley
#

sorry i'm just looking through the c# docs

#

it seems your original way should work

swift falcon
#

so if i give the bytes the other params are not needed

swift falcon
lucid valley
swift falcon
#

but i'll try using your method

#

IF the readin works

#

which it doesnt for now

#

shit im getting a string from a byte[] uhh

#

yeah im smart

#
        string data;
        using (FileStream fs = File.OpenRead(filePath))
        {
            byte[] bytes = Encoding.UTF8.GetBytes(filePath);
            data = Encoding.UTF8.GetString(bytes);
        }

getting no errors here

lucid valley
#

double checking you don't have this save file open in a text editor? that would cause the error

swift falcon
#

hope it works

swift falcon
#

changed to persistentDataPath and now i cant even read smh

#

these are the full errors

lucid valley
#
    private static void SetPrefs(Dictionary<string, object> prefs)
    {
        string json = JsonConvert.SerializeObject(prefs);

        string data = ReverseCrypt(json, JSON_ENCRYPTED_KEY);

        string filePath = Path.Combine(Application.persistentDataPath, SAVE_FILE);
        File.WriteAllText(filePath, data);
    }
    private static Dictionary<string, object> GetPrefs()
    {
        string filePath = Path.Combine(Application.persistentDataPath, SAVE_FILE);

        if(!File.Exists(filePath))
        {
            File.Open(filePath, FileMode.Create).Dispose();
        }

        string data = File.ReadAllText(filePath);

        string jsonFromFile = ReverseCrypt(data, JSON_ENCRYPTED_KEY);

        if(jsonFromFile != null)
        {
            Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
            return prefs == null ? new() : prefs;
        }
        else
        {
            return new();
        }
    }

Try this

merry sequoia
#

Guys how can I access this % value? Please its really important

merry sequoia
swift falcon
#

Ok i fixed it, but everything returns null i guess it doesnt work lmao

lucid valley
swift falcon
#

yeah

#

oh wait no

#

thought the code was for monatti

#

1 sec

merry sequoia
#

i dont really need code

#

i just need for a way

#

to access the animation progress of a blended animation

#

basically the same variable that this line represents

lucid valley
merry sequoia
#

it should be possible since even unity itself is able to display it

swift falcon
merry sequoia
lucid valley
swift falcon
#

BXE"Gd{r`Qa
this is what the save file looks like

lucid valley
#

hum

#

i guess you wanted it encrypted?

swift falcon
#
    public static string ReverseCrypt(string data, string key)
    {
        string result = "";

        for (int i = 0; i < data.Length; i++)
        {
            result += (char)(data[i] ^ key[i % key.Length]);
        }
        return result;
    }

yess

#

that is why im making this

lucid valley
#

you don't decrypt in the read func

swift falcon
#

otherwise i'll just use playerprefs

swift falcon
#

string jsonFromFile = ReverseCrypt(data, JSON_ENCRYPTED_KEY);

#

nope i do

lucid valley
#

oh i'm blind

swift falcon
#

lmao

#

but it still returns null...

lucid valley
#

erm, does that function work like that though?

#

can you encrypt and decrypt using the same function (i've got no idea how it works, might be stupid question)

Nvm, i just tested it and it works

swift falcon
#

the save logs it once

#

but the load logs it 3 times?

#

the last being null

#

ok but i gotta take a shower

#

brb

sacred cairn
#

is there a easy way to totally reset a game object?

wintry crescent
lucid valley
# swift falcon brb

unrelated to your problem but use this instead:

public static string ReverseCrypt(string data, string key)
{
        var stringBuilder = new StringBuilder();

        for (int i = 0; i < data.Length; i++)
        {
            stringBuilder.Append((char)(data[i] ^ key[i % key.Length]));
        }
        
        return stringBuilder.ToString();
}

Using += with strings is not good performance, since it allocates new memory each time which then needs to be cleaned up (bad performance)

stuck forum
#

I'm confused, what is better. This:

    public void SetupGame<T>(T gameMode) where T : GameModeBase
    {
        
    }```
or this?
```cs
    public void SetupGame(GameModeBase gameMode)
    {

    }```
#

honestly ive never used generics and barely see any use case for it... well when constraining it at least

sage latch
#

If you'd return the GameModeBase the first one would be preferred, as you can return the derived type

stuck forum
#

couldn't i return the base as well since the children are inheriting from the base?

sage latch
#

You could, but then the caller would have to cast it

stuck forum
#

ah

#

ok that makes sense. although im not planing to return anything and instead just want to check what sort of game mode has been selected and then set the game up accordingly

sage latch
#

Then I see no difference between the two

stuck forum
#

👍

zinc parrot
#

is there ANY way you can access the origional mesh of a static combined object? since I cant access the triangle lists of a static combined object

late lion
zinc parrot
#

heck ok
and then theres no way to access the triangle lists of it then right? since its not read/writeable?

#

well a way that doesnt require GetData for a graphics buffer(as that doesnt clear memory until the next frame which is bad if I need to do multiple meshes)

tidal dirge
#

Hi, I made an endless scroller game wich keeps going up, question is should I move down my scene or can a transform position go up endlessly

sage latch
tidal dirge
#

ait

hexed pecan
#

You would start noticing glitching because of floating point precision errors, when you get to the 10k-100k range

tidal dirge
#

alright then Ill switch it up

#

shouldnt take too much of a change I think

late lion
zinc parrot
#

Ive wanted to do that, but I have no clue how to write the plugin

#

wanted to also do that for allowing bindless textures but same problem

late lion
#

Though this is more complicated than you need it to be, because it's trying to be async.

zinc parrot
#

hmmm ok thank you!

worldly hull
#

is SO approach similar to interface approach ?

#

scriptable object

late lion
worldly hull
zinc parrot
#

no
its for my asset TrueTrace, I need access to mesh data to build acceleration structures for them

worldly hull
#

never done it before, but it seems great

late lion
zinc parrot
#

hmmmmmmm I could yeah

#

wait
if getdata is done within a task, will that getdata memory get freed?

#

wait no not in the same frame nvm