#archived-code-general
1 messages · Page 41 of 1
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
You can't get the displaced vertices though because they are calculated on the GPU
Most likely
oh it's a shader
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)
^
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.
can't you just ,,export" the image it uses to offset the water?
Using a texture and scrolling it could work. It would be easy to replicate in C#
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
Could probably get away with a pretty big approximation
Lots of room for optimization there for sure
yeah probably. its not something thats super noticable
Honestly it could be just as simple as sampling a texture 2-3 times, depending on how complex you want it
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.
Transfering data between GPU and CPU is expensive
Like reading pixels that the GPU/shader generated
right.. didnt think about reading it lol
This is the reason it would need to be replicated
But maybe a rendertexture, Graphics.Blit etc. could help here
or cheese it. choose wave formula so that its integral is zero => average sealevel is also 0
like a sinus or whatever
Yea
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.
This is a stack trace
but you enable full stack traces from... I believe the console window right click menu
I believe I have found out my problem finally - I had accidentally commented out the rebindOperation.Dispose(); which was the cause of the issue
Best practice for this is to use the using keyword instead of manually disposing. e.g.
using var rebindOperation = whatever;```
this will automatically dispose it when it falls out of scope
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
If the operation lives longer than a single scope, then it may be necessary to manually use Dispose
How would the using line you sent above work without var?
just replace var with whatever the actual type is
I wrote var because I don't know what the actual type is
RebindingOperation?
So that would be used on the line where the variable is assigned?
where it is declared and assigned, yes
The problem is it's declared in a different location from where it is assigned because it is accessed by two functions.
then you won't be able to use using 👍
Makes sense, I'll check out if by simplifying the code that would mess anything up for the next steps of the inputs
Can Someone Tell me Why it Behaving Like This ? And MayBe Some Help ?
At the moment the only thing it is used for accessing a second time is for disabling it
you're setting the velocity which overrides the force added in the same frame. that can cause problems . . .
Can someone please explain why the following happens?
I have resources as follows
Assets/Resources/Entities/Prefabs/resource1.prefabAssets/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?
you are using Resources.Load incorrectly
Wait wrong code just sec (edited. it is being called like the above)
What's the supposed method
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?
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
Did you look at the Emitter Velocity Mode option in the main module?
ah you mean i can manually set in a velocity?
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
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 👍
Is this a viable way to copy a list to a new list?
input is already a list, you don't need to convert it to an array . . .
alright so that's fine then to just put it as a list in the parentheses
i dont want them as references
yes, it's ctor takes an IEnumerable<T> parameter . . .
alright thanks
just test it:
- create a new list with
inputas the argument - change an index value from
temp1 - check if same index from
inputwas updated . . .
byte will never be references, it's a value type
true, i just thought the list itself might reference. i'm sure it'll be fine, thanks.
that's only if you assign the list to another list (since a list is a reference type) . . .
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...)?
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
yea thats what i was afraid of 👍
if you see the new keyword, you can be sure a new list is being created
casting works
((SomeChildScript)_child).SomeValueInChildScript = 5f;```
might be more clear / safe to do something like this though:
if (_child is SomeChildScript cs) {
cs.SomeValue = 5;
}```
why does it need double paranthesis🗿
so you are calling SomeValueInChildScript on the casted result
ohhhh
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;```
i see, that makes sense
It's basically just an operator precedence thing
the . operator has a higher precedence than the casting
Anyone has an idea why it loads resources from parent directory and not the target directory?
read the docs for Resources.LoadAll carefully. anyway, you should drag and drop your array of prefabs onto a slot in your scene, and not use Resources at all
<< Resources.LoadAll("Entities/Prefabs")
Empty Object[]
⚠️ Wtf why empty now, but parent directory loads them?
this is one of the quirks. don't use Resources.LoadAll
I have to load many resources at runtime
(so I'm loading and caching them)
thanks tho
you can drag and drop
everything onto a slot
you do not need to use Resources.LoadAll
I can't drag and drop at runtime
this doesn't make sense
in your editor
I know
I need to dynamically load at runtime not at compile time
it doesn't work that way
resources is still "compile time"
Ok
if you create a resources folder in your player build, it will not be read
does that make sense?
Yes
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?
The misunderstanding happened when I implicitly thought if it has the Load method then the resources are copied somewhere the game can read after compiling
But since it doesn't copy them and they are squashed into the game files then my method is invalid completely
Now how do I drag and drop 200 items
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
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?
Use Rider
it will link to the docs pages
If you're modifying URP you should be using an Embedded Package:
https://docs.unity3d.com/Manual/upm-embed.html
Costs too much
then you'll just have to keep a link to the docs open. it's the same deal . . .
No need to be rude
wasn't rude at all, just mentioned the alternative . . .
Ahh, I've missunderstood then
!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.
@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
Can anyone help with this jetpack script I made? It works but I can't, in anyway, control the movement of my camera or my 3D Player model. Can anyone help? Here is the link https://paste.ofcode.org/6L6JWF2xv9tkk8FXj7tke9
Thanks for your reply. I had already done this. Sorry if it wasn't clear in the original message.
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?
Regenerate project files maybe?
Seems like something you could/should use the Job system for, and have all the car data in native collections
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
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.
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.
Can't you make world space UI for the enemies?
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
yes, we need code and screenshots if available . . .
Sure thing! Should I start a thread?
are you converting from screen to world or world to screen?
Can't you use Sorting Layers for that?
i got 3 set up for my game right now, and it works perfectly
if this is 2d, you can use sorting layers . . .
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
yourCam.ScreenToWorldPoint()
should work
ok i fixed it, my IV key was incorrect. So i generated another IV key using some cranky ass websites and used that. it now works kind of
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?
Game reads that data from scriptable objects
🚫
CustomWeapon class that changes behaviour depending on said data
just make prefabs
custom ability system
since this is a single player game, do it as straightforwardly as possible
gradually add complexity when you come up with specific designs
Heyy, so i'm implementing enemy movement.
- The enemy will face towards the player
- 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
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
Thats the issue im facing - how can i update velocity without making the object accelerate?
i was wandering if you could separetly change the velocity direction via script
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
Oh indeed, it worked, i had a wrong understading of velocity, i thought its addable like AddForce
thank you man
i mean you can increase it, but it's a Vector3 so that would require using += instead of just =
thx a lot for clarifying
I'm using photon pun, both players can create servers fine, but neither can join the other's server.
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()
use interfaces
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?
But don't you have to either make the functions public, private, or protected if you do that?
?
Oh wait nvrmind
I don't understand what that has to do with interfaces
I was thinking of abstract functions
interface members must always be public actually
Oh well is there any way I could allow them to be private? I wonder if unity uses reflection for its system
Unity does indeed use reflection
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
I suppose I will stick with abstract functions, as they don't require implementation on a child class (wait no virtual)
event
Thanks!
i need to create a collider via script. I'm thinking of scripting a mesh and then just adding collider as component?
either instantiate a prefab, or use AddComponent
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
looks like it's resetting to 1 properly in the else, no?
presumably if(itemCollect.alive) is becoming false
yeah but when the level resets the original value is still there
You're using Time.time
Time.time doesn't reset when you load a scene
This? https://docs.unity3d.com/ScriptReference/Time-timeSinceLevelLoad.html
But I really don't recommend either. I would just make my own timer with Time.deltaTime
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.
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
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
the most reliable way (which AAA mostly uses for this kind of thing) is marking climbable ledges with a collider and then just overlap-checking for them from your player position. These markers can be automatically generated or manually authored. The benefit of markers is that your generator algorithm can be arbitrarily expensive.
Yeah I didn’t want to manually create them. That’s what I was doing but it was a pain. How does the algorithm work? Is it voxel and calculus based, does it cast from above?
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?
there is no magic to it, multiple ways to detect the ledge, you already got one way, the rest depends on your specific game (deciding which ledges should be climbable in an algorithmic way)
How do I crawl through the scene like the navmesh generator does?
If you just combine the marching cubes values you’ll generate one big island
you could just raycast down in a grid pattern, or overlap-sphere in a grid pattern, the simple ways all come down to sampling the colliders in the scene at a certain resolution, potentially in a volumetric way
@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
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
You could just, maybe, move the meshes close together and pretend
the raycast can be in any direction
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
how do i make like a dev chat and buttons like discord in unity 2018.36f1?
either learn UIToolkit would probably be easier to get a modern webUI, or learn how to work with the old school UI and it's components
is there any guide for it?
How could a buoyancy solution work? Does the force generally get applied at the corner bounding box positions or something?
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.
how do you connect one void with another?, rn it doesnt want to do anything with b if its in another void
Your trigger likely isn't firing in the first place
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
possible?
Normally you can explain it in text rather than doing an art project
Because nobody knows what that means
You want to authenticate users over the internet?
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
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
ofc is possible
you can store the info in a file or database as well
using a gameengine for this is kinda silly
but totally doable
and?
I don't know why you would store that in a file or database
wat?
Why would you do live chat with a database
all chat systems have databases
why would you not
how would you moderate messages
etc
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
gameplay server has not much to do with how you deal with your messaging system
most of that stuff lives in a database
you can disagree all you want it's pretty known fact
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
It'd be much more reliable to just use a pre-built service like Vivox https://unity.com/products/vivox
if someone joins and you aren't storing that the new joiner has no idea what was said in chat
Most people don't care about chat messages that late
I play mostly FPS games
not card games or whatever
so again, it depends
Debug is working, if() is not
bro this is out of the scope of the original poster's question
they said a Discord system
discord uses db
If i put the if() inside the trigger, it will, but i want to destroy the gameobject
Child start not being called
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
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
That's just setting position. It can't possibly break frustum culling or spawn objects.
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! 😄
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
is AtlasSlot the class name? if so, you need a reference to an AtlasSlot object . . .
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...
Interesting, I've never come across this before - how is that different from referencing the class?
it's not a static method therefore you have to call it on an instance of the object
you only need to reference the class to access a static field. if you want to use a non-static member of a class, you need an instance of that class . . .
which means you also need to tell it which instance of the class you want to call the method on
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
that's how everything works. Time.deltaTime is a static property, therefore you reference Unity's Time class to access it . . .
hmmm, did you start with any beginner c# tutorials, that's a #💻┃code-beginner topic?
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 . . .
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"
don't make the method static . . .
o
the bug persists if I remove static from the method
also this should absolutely not be a singleton, get rid of the public static AtlasSlot Instance
right because you still aren't bothering to get a reference to an instance of the object
you're just brute forcing your way through using the static keyword which is not going to do what you actually want it to
get a reference to an instance of the AtlasSlot object. since it is a component, it's fairly easy: https://www.youtube.com/watch?v=Ba7ybBDhrY4
and #💻┃code-beginner next time
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
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
OH so I need a reference to the AtlasSlot script IN the ItemPickup script?
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
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
@mental reefMath.Clamp(myRotationEuler += mouseDelta, min, max);
Thank you for your reply. How exactly would I add this code to a script?
By using critical thinking
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
when i instantiate an instance of a gameobject does it generate a different guid or inherit the guid of the gameobject it instantiated from?
The unity GUIDs have 2 parts I'm pretty sure
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
this is my PlayerCamera script. I'm kind of lost where I'd add that code to
This is why we don't copy code from youtube
You need to understand how euler angles work before proceeding
it's pretty simple
I agree with you. I am learning quick and have a 2nd project where I do not receive help and do what I have learnt.
You don't need to lerp your rotations in the update loop
show me your cameraSmoothTime variable
I did try to kind of copy the pivot etc
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
I was following Sebastian Graves tutorials on 3rd person camera/movement. What you say does make some sense. I really do appreciate the detailed explanation. I have screen shot it to read back on
First of all you should probably learn C#
and understand what we're doing internally with the values
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
for trivial camera setup you can use cinemachine
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
I used that and honestly do not remember why I stopped using it. I guess because said person had a few things I wanted in my game so would be easier to follow along and to copy paste?
That's not going to fix his problems
Telling someone to install bloatware doesn't fix the issue of not understanding how to rotate an object in sync with the mouse
lmao cinemachine is certainly not "bloatware"
i just read the rest of your convo, you're right, CM will do more harm than good. the guy needs to learn the basics first.
@mental reef find a tuto that walks you through the basics of 3d transforms. you need to be familiar with things like dot product
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)
3rd person camera is all about projecting values in camera space and once you get this the rest will be easier
Coming from a beginner's POV (at least in regards of unity), I thought CM was fairly simple to pick up and get the hang of
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
yeah forget lerp and smooth until you get the motion right
I think it got rid of many redundancies for me
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
Ah I see
and most unity youtubers are no good for the same reason
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.
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
...or catlikecoder. see which one is clearer to you.
I have been watching code monkey. I will start watching them soon
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?
why would you need to call findall if you're storing your instantiated objects in a list
cause the list will contain a mix of other prefab instances
just make a list with the type of object you care about
that's the issue, all the objects in the list are what i care about.
It will look for that specific object instance(the prefab). If it's not in the list it will not find anything.
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?
Prefab != Instance of a prefab. From the computer perspective "they're 2 completely different objects, wtf are you talking about"
Not if you compare with the prefab (asset) directly.
If you do prefab (asset) == prefab (instance), it will be FALSE
that's what i wanted to make sure
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
Or a dictionary of lists where prefabs are the keys.
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
Telegraph?🤔
basically a warning area of an attack
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
in this case the latter
Oh, ok
i guess i can technically run them into different bins but i worry about wasting too much memory.
The first time I heard that word I'm that context, but ok.😅
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
To me it seems like you want a pooling system eye sea, is that correct?
yes
What do you mean by a "bin" here?
an array for each category of telegraphs
so one array for circle telegraphs, one array for a fan telegraph
bin == pools
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'
right an object pool
i guess from there it becomes a matter of lining up the timings
timing basically being
I'm not sure why lining up the timings is the issue
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?
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
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.
Why does the pooling system needs to know anything about timings or anything else related to attacks??
not the pool system itself but once i pull out of the pool.
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.
i still need to load the telegraph with how long the telegraph will last
How is loading related to time?
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
It seems like you're coupling the telegraph with the execution logic
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.
Why does the telegraph script needs to hold the data on the timing? It should receive that data from the attack.
right the attack skill would have a float array of the timings for it.
Why is it an array though? Should there be one timing for one attack?
basically telegraph[0] will be given 1.5 seconds, telegraph[1] will be given 2.0 seconds
so on normal attacks yes it will run on animation length. But i'm trying to expand it to a single attack with multiple telegraphs.
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.
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'
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..?
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.
I'm surprised you haven't heard the term before.
It is inescapable when a new Dark Souls gets released and some enemy has really hard to tell attacks appart from each other
Thanks
Have you seen the sentence 'wind up animation'?
I've played 2 out of 3 dark souls but I've never heard that word.
The only term that comes to mind is area of attack indicator or something.
Aight. Guess I've been living in a cave
darkened your soul it seems
So, it's some kind of subtle indication for a player of an upcoming attack
And that's correct.
The boss behaviour dictates that in these 4 locations, after .5 seconds, damage will be applied in that area.
The boss behaviour also says 'spawn 4 telegraphs on these 4 locations that will last for .5 seconds.
The telegraphs don't have to know anything about the boss, the attack that they are performing or anything.
subtle or obvious
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
the boss itself doesn't have to remove the telegraph.
The telegraph can be responsible for removing itself
some external manager i presume?
oh ok
so same coroutine behavior
but when coroutine end, then return to pool
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
right which i have a script for canceling telegraphs in the event they get stunned
then the BOSS should disable the telegraphs it has spawned
By the way, Unity has a built in generic pooling system that you may or may not want to use.
https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
i think i ran with a queue system before
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
Mhm, whichever system works for you
somehow any version that is later than 2021.3.16f1 crashes
3.16-3.18f1
2022 is fine tho, but thats in beta
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;
currTarget is null. where do you assign it?
and are you null checking currTarget before you execute the code where your error is happening?
Oh haha that solved it! how silly of me :P thanks :)
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
the GetEntry method returns an AssetTableEntry, that has an Address property that will allow you to load the asset from Addressables
https://docs.unity3d.com/Packages/com.unity.localization@1.4/api/UnityEngine.Localization.Tables.AssetTableEntry.html#UnityEngine_Localization_Tables_AssetTableEntry_Address
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
did you drag an Image component into the inspector for the image variable?
and you are certain that newItem is not null?
theres no way it could be after collecting an item I just cant see how through the 3 methods or so
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);
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
what is line 20 of InventoryItem
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
huh
clones of the inventory item
ah wait, i forgot the quotes so that's on me actually
which line did it come from though
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
well there you go, newItem is null
Show us the code that executes InitializeItem
!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.
what calls AddItem
How deep it is 🙂
christ this is such a long chain of methods passing null around
code
And who calls Initialize ?
nothing?
well there's your issue then
alright so do i put initialize in the start method
No, better look carefully to the tutorial, idk
alright the collector script was from a different one a while ago so that y i dont know
ill find it
Send us the link to the tutorial
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
instead of passing item which is null and would need to be predetermined on this script surely you can pass in the collectible that you collide with, no?
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
your check to see if you can add an item is what is causing your error in the first place
are you sure?
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()
is the NRE in the same place as before? or is it somewhere else now?
its this weird one that gives like no info
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
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
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 🤔
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
Hey ppl, got a quick question.
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 ?
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.
- 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.
- 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?
Well i got the code for a dictionary and some JSON stuff.... So i guess that works. But uhh i would have to remove some code. Mind if i make a thread for this?
sure, go on
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?
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?
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.
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.
what is IDE?
Visual Studio is an integrated development environment
how do i set it up?
By reading the links I've given?
ah
all of my prefabs has same components ()
@cedar pivot Don't cross-post. And this is not a code issue
Vivox did not work there is not a samples dir in the windows 10 SDK
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
wouldn't you just multiply the input vector by Momentum?
Or I guess you're wanting a remapping function
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
You'd do something like this:
float minMomentum = 1;
float maxMomentum = 1.15f;
float inputStrengthMin = 1;
float inputStrengthMax = 0;
float t = Mathf.InverseLerp(minMomentum, maxMomentum, Momentum);
float multiplier = Mathf.Lerp(inputStrengthMin, inputStrengthMax, t);
inputVector *= multiplier;
Here's a whole thread discussing the concept: https://forum.unity.com/threads/re-map-a-number-from-one-range-to-another.119437/
it's a remapping function
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
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?
I mean, since Vector2.left and Vector2.right are just short versions for new Vector2(-1,0) and new Vector2(1,0) respectively, I guess you could use Vector2.zero, but that'd probably mean you'd need to make the second argument 2 times bigger on the x
wait, no, I misunderstood what BoxCast does
you could either cast it from the leftmost position to the rightmost position
something along the lines of
Physics2D.BoxCast(bCol.bounds.center + Vector2.right * 0.1f, bCol.bounds.size, 0, Vector2.left, 0.2f, wallLayer);
or something
or just use two casts as you said
This solution worked! All I had to do was make the second arguement bCol.bounds.size+bCol.bounds.size. Thanks!
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
Which lines are 36 and 69?
what does GetPrefs() do?
getprefs reads from a text file, decrypts it and turns the JSON string into a dictionary
It's returning null so you have to show it
Setprefs does the opposite
well it seems that GetPrefs returns a null ref
so when you call the function, it spits a Null Ref exception
try a try statement to verify
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
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
and how can i do that?
what IDE do you use
return new()? never seen that
new C# 11
visual studio 2022 (the purple one idk whats it called)
new() is simplified version of new Dictionary<string, object>();
and next to the line click to add a break point
funtion break point?
if you run unity, and it has been attached to VS, it should freeze and send you to the point where the program broke
okk
im confused af 😭
or just do Debug.log(jsonfromfile) before the last if, and see what it prints
and maybe a debug.log(prefs) before you do return prefs
toggle break point?
do the debug logs
break points are such a pain in unity projects in my experience
not in my experience
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();
}
The same way you check if jsonFromFile is null
?
i check if it's null (aka nothing is there yet) and if so throw out a new dictionary to use
Yes, and you can do the same to prefs
but if that is empty, what should i return?
Well, what do you want to happen in that case?
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 😃 🔫
That's a bit convoluted but 👍
if it aint broke dont fix it
made it smaller yeaaah
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();
return (prefs == null ? new() : prefs);
oohh didnt think about that lol
but uhh yeah idk how to fix this now.... what a joy
try
Dictionary<string, object> prefs = JsonConvert.DeserializeObject(jsonFromFile) as Dictionary<string, object>;
if (prefs != null)
{
return prefs;
}
else
{
return new();
}
maybe
got m thanks
o
that
i am not using dataPath instead of persistentDataPath and it works
thanks for all the help guys!! <3
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?
what do you mean doesn't run?
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
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
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
Then that is an issue with your code in general
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.
isGrounded() is a public bool and I'm not sure how those are called in general. I thought it happened once every frame but apparently not. Any idea as to how they work?
https://gdl.space/ohexayitid.cs
I'll be back to answer any questions about this code. Thanks for the help so far nonetheless
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
Is there a question here? This code is strange in several ways though.
2nd debug log and lerping happens after RecoilTimeStamp reaches 1, why?
it won't, you have an if statement there
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
I tested it and it does
try 1f-(RecoilTimeStamp*20)
to speed it up
yeah that's why I'm confused, I'm supposed to do my stuff when RecoilTimestamp < 1
it is doing that
I'm trying to figure out why you're doing the Lerp in reverse
and then doing 1 -
show the code that errors
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
that was for me to test the "t" of the lerp to see what's going on
that worked thanks
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.
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
well, looks like either player or player.Animator is null
either use some logs to find out which or attach a debugger
will do, thanks for the help!
I'm getting some inconsistent behaviour working with floats:
Can anyone possibly explain?
dont use == with floats
oh crap
use Mathf.Approximately()
what do?
lol it was because I was accessing the player via its parent lol--that's why it was null
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?
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
Personally, in a grid scenario, I prefer to have either a 2D array of all grid cells and access the neccesary one by adding or subtracting 1 from one of the coordinates of the grid position of the player, or having each grid cell as a gameobject holding references to nearby grid cells, linked-list style
I'm using a combination of both to validate that the grid is correct and potentially store information in the array
a raycast feels too risky
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...
Sure its not as best of a solution as others are.. but if you absolutely need to do raycasts, you can make it work
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
you will just need to do some calculations to ensure it actually gets the grid correctly
Oh my player can indeed move by ignoring the grid cells, the cells are only needed for planting and building paths.
oooh yea raycasts aren't a bad idea then
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
why not? You can step through a 2D array like coordinates
you can always store the grid coordinates on the grid cell gameobjects
then, by raycasting one, you can do calculations off of that
uh, i would advise against this if you have a large grid
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
I mean when I was playing around with large grids, I had to pool my gameobjects, but that's a separate issue
but yea I also had an array
with everything
Back to the drawing board then haha
with my hybrid approach I round the raycast hit, cast that to an int, voila array index
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?
anyone able to give me some help making a unity loadout system for my multiplayer fps thats running on photon
ah, no
I'd send you my old code with this exact problem, but I lost it
it wasn't great, so it's for the better anyway
It was something along those lines
struct Tile
{
int x;
int y;
}
Vector2Int mapSize = new Vector2Int(10, 10);
Tile[,] tiles;
private void Start() {
tiles = new Tile[mapSize.x, mapSize.y];
}
you can extrapolate from that
I've shared the script, @me when you want to discuss
I just wrote in a minute, obviously Tile struct is a separate file, probably other things must be there too, like tile type or some data, you must check if you're not going out of bounds, bla bla bla, ya know, all the small stuff
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.
without post processing? tough
probably would need a custom shader for that
or you could fake it by having an image with transparency behind the button, that scales up on hover, with a "glow" texture on it
and maybe change the color of the button to match
A lot going on in this script, maybe you could phrase the current problem again?
isGrounded doesn't seem to be updating properly during Sprint and dashJump
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()}");```
Ah, sorry
Yeah
I am a little confused on exactly where the problem is with which variable a method
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()
How often is isGrounded called? I got it from a yt tutorial but they never really said
Something like
bool isGrounded;
// And change the isGrounded() method to
bool GroundCheck()
{
isGrounded = Physics.BoxCast(...)
}```
It's called every time you typed isGrounded() in the code
Which looks to be like 10+ different places in that script
Really?
Now that I know that I have some tidying up to do
Also, should GroundCheck in this example be a void instead of a bool
This seems like the best route
Youre right it could be void
why no post processing, though?
VR. I'm just staying away from post
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?
a little bit of postprocessing won't kill you
nor the user of the headset ;P
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
Yeah
Well not directly a fix, but it could make it a bit more readable
And easier for you to debug
What is the difference between update and fixed update?
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.
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 👍
Hey i got a question again
dataPath and persistentDataPath are both not writable
i can read from them
but not write
where do you get the datapath and persistentdatapath from, and why do you want to change the path to the data?
seems rather obvious they would be read only
well i have the player save file
and i want to write to "Application.persistentDataPath + player.feverdream"
and read of course
but it won't let me
- use Path.Combine(), that will add the necessary
\between the two paths
string filePath = Path.Combine(Application.dataPath, SAVE_FILE); still gives the same error
yeah
humm, well sharing violation seems like you are reading and writing at the same time in two streams?
private static readonly string SAVE_FILE = "player.txt";
show the code where you read it and write it
not that i know of
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
show them both
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
using (FileStream fs = File.OpenWrite(filePath))
{
fs.WriteAllText(filePath, data);
}
try using it like this for both
alright
filestream does not contain WriteallText
it does have Write but that is for a byte[]
it might compile fine since a string is just char[] might have a conversion
How can i access this percentage from my code, so i can for example print it in a debug log
nope it just throws errors
FileStream does not contain a definition for "WriteAllText" same with "ReadAllText"
byte[] bytes = Encoding.UTF8.GetBytes(data); then use fs.Write()
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
oh btw file stream wants a offset and count??
i just have the file path and the bytes
im dumb lmao i'll look at it
i guess 0, and then byte array length. But see if WriteLine() exists
WriteLine does not exist
Oh i can just use Write
since i give the filepath in the using statement
so if i give the bytes the other params are not needed
welp it doesnt
is there a line number in the error?
no i just cant access the files
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
double checking you don't have this save file open in a text editor? that would cause the error
hope it works
nope
changed to persistentDataPath and now i cant even read smh
these are the full errors
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
Guys how can I access this % value? Please its really important
No its not, it shows some messed up value since im trying to acces a blendtrees animation cycle progress and not a normal clip
Ok i fixed it, but everything returns null i guess it doesnt work lmao
did you try what i put above?
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
maybe ask in #🏃┃animation ?
it should be possible since even unity itself is able to display it
your code works but also returns null
might be worth a try
log what you are writing
BXE"Gd{r`Qa
this is what the save file looks like
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
you don't decrypt in the read func
otherwise i'll just use playerprefs
wait what
string jsonFromFile = ReverseCrypt(data, JSON_ENCRYPTED_KEY);
nope i do
oh i'm blind
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
the save logs it once
but the load logs it 3 times?
the last being null
ok but i gotta take a shower
brb
is there a easy way to totally reset a game object?
yes
in editor, make it a prefab
destroy it, and spawn a new one from the prefab when you want to reset
no other way, I think
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)
alright
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
If you'd return the GameModeBase the first one would be preferred, as you can return the derived type
couldn't i return the base as well since the children are inheriting from the base?
You could, but then the caller would have to cast it
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
Then I see no difference between the two
👍
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
I doubt it. The mesh in the MeshFilter is replaced with the combined mesh at build time. I wouldn't be surprised if the original mesh just isn't included if it's not referenced elsewhere.
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)
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
If you can moving the map downwards instead of the player is the best way
ait
You would start noticing glitching because of floating point precision errors, when you get to the 10k-100k range
You could start looking into writing a native graphics plugin, to bypass GetData and handle the buffer read yourself. But it's low level, you'll have to implement a specific graphics API, or multiple if you want to support more than one.
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
This could be a starting point:
https://github.com/yangrc1234/UnityOpenGLAsyncReadback
Based on https://github.com/Alabate/AsyncGPUReadbackPlugin. Plugin for Unity to do async gpu readback in OpenGL environment. - GitHub - yangrc1234/UnityOpenGLAsyncReadback: Based on https://github....
Though this is more complicated than you need it to be, because it's trying to be async.
hmmm ok thank you!
Are you making a mod or something? Are you not able to read the assets in the editor before a build is made?
someone introduced me breaking down parts of functions into individual SO and implement it into the script
no
its for my asset TrueTrace, I need access to mesh data to build acceleration structures for them
never done it before, but it seems great
You could make an asset post processor for models. Since 3D models are imported as GameObjects/prefabs, you can read the Mesh from the MeshFilter component and even add your own components to the prefab or embed sub assets. Then you can do the data structure calculations offline and bake it into the model instead of doing it at runtime on the first frame.