#archived-code-general

1 messages ยท Page 57 of 1

quartz folio
#

visual studio code bad (with Unity) ๐Ÿคท

heavy hornet
#

Yeah, well it's the only option for me...

quartz folio
#

Are you a student?

heavy hornet
#

Yes

#

I could use Rider...

#

but I don't know it...

#

Is that the "preferred" IDE for Unity devs on Linux?

quartz folio
#

It's the preferred IDE on every platform if you can get it

#

VS Code is the least supported one

heavy hornet
#

Alr I'll try it

#

But it'll cost me when I'm not a Student anymore...

quartz folio
#

They're not supporting VS Code's debugger plugin, and they don't even add the VS Code package to new Unity projects any more

heavy hornet
#

Yeah, I saw that

#

149โ‚ฌ/year for Rider o.O

quartz folio
#

I pay for Rider, it's very good. When the EAP is running you can also use that for free.

#

The cost goes down over the course of 3 years

heavy hornet
#

I mean yeah, JetBrains IDE's are good... but I don't have the money to pay 149โ‚ฌ for it as a hobby

quartz folio
heavy hornet
#

I have Student stuff already

#

I use IntelliJ Ultimate

dim spindle
#

is VS fine (not code)

quartz folio
#

Rider should feel very familiar then! Otherwise, you'd probably get more out of asking about VS Code on the forums

#

VS is completely supported

heavy hornet
heavy hornet
dim spindle
heavy hornet
#

Hmm... true

quartz folio
#

Also should note that former student license holders get 40% off so you wouldn't be paying that 149โ‚ฌ for the first year, but anyway I'm sure you can figure it out, maybe when you're no longer a student Unity will have updated to .NET 7-8 and VS Code will become supported again

heavy hornet
#

:o 40% off sounds nice

heavy hornet
#

ยฏ_(ใƒ„)_/ยฏ

arctic lintel
#

is there a way to put my custom enum List as argument in PhotonView.RPC using pun2?

arctic lintel
#

ok

heavy hornet
#

Ooohhhh.. thanks Rider ig... that is cool ngl

lost dome
#

How can I change an input joystick axis from being from -1 to 1, to 0 to 1?
Basically, -1 = 0, -0.5=0.25, etcโ€ฆ

quartz folio
#

(x + 1) * 0.5

bitter saffron
#

Is it possible to use Animationcurves in the Unity UI System or do we have to make or own splines?

leaden ice
#

Kinda depends what you mean by "use" here

#

use them to do what

bitter saffron
#

I mean like a slider or button, just drop in an animationcurve so players can for example tweak a curve to determine spawn behavior in the build.

leaden ice
bitter saffron
#

Yeah but thats inspector only, isnt it? What I mean is instead of this here:

#

I want something like this here I did for the level nodes:

#

I mean it is programmable but maybe unity has some ready to use Unity.Ui - Animationcurves where I just have to swap textures or something like that

leaden ice
leaden ice
#

or what it has to do with curves/animation curves

bitter saffron
#

nvm

leaden ice
#

Unity has a Spline package, if you're interested in splines.

pallid sail
#

isnt code i dont think but anyone know what the error
assertion failed on expression : 'Get SystemInterested(transform, system) != enable' means, 4 of em pop up after I end my play scene

bitter saffron
dim spindle
#

Does anyone have an idea about this? Other inputs work fine, and it works on windows, but just not on linux its very weird

#

I dont think its input settings? And im not sure what physics settings would make it not work on linux

#

Ok SO rays are getting cast at the correct position

#

between linux and editor in windows, the ray coordinates can be the same

#

but the item will only pick up on one system

#

hmmmmmmmmmmm, so i would assume its a physics problem between target systems

#

but why would it be different?

plucky inlet
dim spindle
#

I can try that yeah

#

layermask added, same result

#

including in logs

jaunty sleet
#

I can not get my binary formatter save to work for the life of me

leaden ice
jaunty sleet
#

why?

leaden ice
#

It's dangerous for your users

jaunty sleet
#

what should I use instead then?

leaden ice
#

the article mentions some alternatives. You can also use well known JSON serilializers like Unity's JsonUtility etc...

jaunty sleet
#

maybe it will work if I just switch the serializer to that then, because I couldn't find the issue with my code for the life of me other then the data just not coming through correctly

leaden ice
#

Well I mean in your test you're not even saving the data at any point

jaunty sleet
#

?

leaden ice
#

you never call saveLevel

#

so IDK what you think you're loading.

jaunty sleet
#

// test save and load methods with test note data
public static void test()
{
note[] notes = new note[3];
notes[0] = new note(1, true, 10, "note", "turnRight");
notes[1] = new note(2, true, 25, "note", "turnRight");
notes[2] = new note(3, false, 40, "note", "turnRight");

    foreach (note note in notes)
        Debug.Log(note.ToString());

    saveLevel("test", notes);
    note[] notes2 = loadLevel("test");

    foreach (note note in notes2)
        Debug.Log(note.ToString());
}
leaden ice
#

oh I missed it somehow lol

jaunty sleet
#

lol

leaden ice
#

you should be using using statements btw

#

whenever dealing with things like FileStream

jaunty sleet
#

what does that do?

leaden ice
#

there's a risk you are not closing your streams properly

#

it ensures streams are opened and closed properly.

prime sinew
#

I see there's resizable window, but yeah, shame. Thought there'd be more

jaunty sleet
#

then I also don't have to close it after right?

leaden ice
#

Or just use File.WriteAllText / File.WriteAllBytes and skip all the stream stuff

jaunty sleet
#

I like the streams lol

#

Now I just have to figure out how to change my code to use JSON serializer

#

also, JSON stands for java script object notation, but I can use it in c#?

prime sinew
#

It's just a text format used to represent data. Not really a language or anything

verbal pebble
#

No idea if this is the right place for it. My player character is animated so his sprint is slower at the start, but full speed during the loop. The animations have no root motion. I'm assuming this is a code thing though, I need to figure out how to change the player character's speed so he's slightly slower at the start of the sprint with a pause before going full speed.

#

Had a look around online and couldn't quite find any info on what I'm trying to do, so there might be a term for it that I'm not aware of.

verbal pebble
jaunty sleet
#

if I save a json file to a folder using write all text with the same name as a json file already there, will it overwrite the old file?

jaunty sleet
#

that's probably what I'll do

jaunty sleet
#

nvm I am dumb

inner yarrow
#

What would be a good way to figure out all of the objects that are visible from a certain point in my scene? I considered raycasts, but figured that that would be bad for performance, and it would be very precise for scenarios where the center isn't visible, but the edges are.

inner yarrow
potent sleet
cosmic rain
#

It's not gonna be precise either. How do you know what to raycast against if not the center of the objects?

#

Unless you raycast per pixel on the screen, which is really gonna kill the performance.

#

I'd use what DROD mentioned or maybe iterate all the objects and do some math involving their bounding boxes, view point and frustum angle.
There might be a utility method to make it easier. That would still be pretty heavy depending on the number of objects...

inner yarrow
#

Yeah, that's kinda why I was hoping that there's a better method. The renderer.isVisible thing I don't think would work very well because it's not a camera, and if I'm reading correctly, that returns true if it's visible by any camera.

cosmic rain
maiden breach
#

Well you could put a camera there that only renders a certain layer. @inner yarrow

#

Duplicate the object your trying to detect as a child, put it on that layer and check its renderer etc

inner yarrow
cosmic rain
potent sleet
maiden breach
cosmic rain
#

Maybe GeometryUtility.TestPlanesAABB the relevant objects?

inner yarrow
inner yarrow
potent sleet
#

is it a camera effect only ? or something

swift falcon
#

yo guys anyone know how to add a timer until the next line of code is activated?

maiden breach
swift falcon
#

like a stopwatch

potent sleet
inner yarrow
maiden breach
swift falcon
#

oh XP

swift falcon
#

oh

maiden breach
swift falcon
#

ok ill read the doc and pull up a few vids, Thanks for pushing me in the right direction :>

cosmic rain
#

Or raise some flag and wait in update.

pseudo scarab
#

Hello I'm setting up a bunch of raycasts for hit detection in a melee game, I need to be able to set these points manually and I was wondering if its possible to create these positions through the inspector instead of adding empty gameobjects to each weapon to use as points. I tried using a list of vector3's but there's no visual for the placement of these points

maiden breach
true sapphire
#

quick question: can you change the outer spot angle of a Light 2D in script?

pseudo scarab
#

o why didnt i think of that lmao

#

ty

true sapphire
#

oh lmao ty i didnt realize point light and spot light referred to the same thing

#

appreciate it

potent sleet
swift falcon
#

my OnCollisonEnter is bugging out it keeps saying its wrong but every other script reference looks like this plz help

leaden ice
swift falcon
#

opps sorry here:

leaden ice
#

You can only have yield return in iterator methods, which this is not one.

swift falcon
#

oh

leaden ice
#

an iterator method must have IEnumerator as the return type, not void

swift falcon
#

welp back to the drawing board i suoppose

leaden ice
#

why?

#

Just change the return type to IEnumerator

swift falcon
#

oh

leaden ice
#

OnCollisionEnter can be a coroutine

swift falcon
#

ok

dim spindle
#

Ok, I am really confused. I am trying to get a Raycast to work on both windows and linux. For some reason, my item pick up script works on windows, and in the windows editor but NOT on Linux.
This is the code for detecting a raycast. On linux, I get the print for "Pickup Press", and the print for "Ray Created" but not the "Ray Hit an Object". On windows, the "Ray Created" Coords MATCH the linux ones in my test case, but the linux one doesnt get the raycast to hit the item.... its really weird

public void Pickup_Pressed(InputAction.CallbackContext ctx)
{
    Debug.Log($"Pickup Press: {ctx.performed}");
    if (!ctx.performed)
        return;

    RaycastHit hit;
    Ray ray = main_camera.ScreenPointToRay(Input.mousePosition);

    Debug.Log($"Ray Created: {ray.GetPoint(0f)}");
    if (Physics.Raycast(ray, out hit, inventory_grab_range, mask)) // Do a Raycast with only layer 8 (Items)
    {
        Debug.Log($"Ray Hit An Object: {hit.transform.gameObject.name}");
        Transform hit_transform = hit.transform;
        GrabItem(hit_transform.gameObject);
    }
}
leaden ice
dim spindle
#

they are kinematic atm

#

for testing

#

the code runs whenever i press E

leaden ice
#

that doesn't really answer the question ๐Ÿ˜‰ Kinematic objects can move via script

dim spindle
#

ok well they are not moving

leaden ice
#

Is anything messing with Time.timeScale or Time.fixedDeltaTime or Physics.autoSimulate ?

dim spindle
#
  1. No, 2) uhhh No, 3) i dont think ive ever seen that
#

would it only be in my own codebase?

#

i can do a search through my IDE

leaden ice
#

It's possible for plugins/assets to change these things

#

but not likely. Worth looking though

#

I know for example Obi Rope messes with autoSimulate for example

arctic ingot
#

Well this is interesting...
My editor has crashed out of nowhere after putting the same object in both the Viewport and Content section of a Scroll Rect. It seems to crash every time I open the specific scene where I did this...

[C:\build\output\unity\unity\Runtime\BaseClasses\PPtr.h line 271]


=================================================================
    Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================

=================================================================
    Managed Stacktrace:
=================================================================
      at <unknown> <0xffffffff>
      at UnityEditor.AssetDatabase:OpenAsset <0x000f6>
      at UnityEditor.AssetDatabase:OpenAsset <0x0009a>
      at UnityEditor.AssetDatabase:OpenAsset <0x00092>
      at UnityEditor.ProjectBrowser:OpenAssetSelection <0x001aa>
      at <>c:<.cctor>b__1_2 <0x0009a>
      at UnityEngine.GUIUtility:ProcessEvent <0x00114>
      at <Module>:runtime_invoke_void_int_intptr_intptr& <0x001b5>
=================================================================
Received signal SIGSEGV
Obtained 2 stack frames
RtlLookupFunctionEntry returned NULL function. Aborting stack walk.
<Missing stacktrace information>

#

(btw I shortened the stacktrace bottom up to fit inside the Discord character limit)

leaden ice
arctic ingot
#

Already done, mainly was hoping someone had an idea here ๐Ÿ˜…

dim spindle
arctic ingot
#

Thing is...this happens all the way from 2020 to 2023 alpha 2

dim spindle
#

can you reproduce it though? if you do that again in another scene does it die again

leaden ice
leaden ice
#

Unity will be able to reproduce it with debugging symbols and figure out where in their own native C++ source code it actually happens

#

without that it's shrug city

arctic ingot
#

One thing to note, if I force it to load a different scene, it doesn't crash

dim spindle
#

wdym by that

arctic ingot
dim spindle
#

@leaden ice anything else that would kill it? and something that would ONLY happen on linux?

#

specifically ubuntu

#

if that matters

leaden ice
#

maybe the "both" input mode doesn't work on Ubuntu

dim spindle
#

that WOULD probably be a good idea

#

yeah

#

maybe

#

i just used the old one because i new the magic trick for it and it still worked

#

so why change it lol

leaden ice
#

this could be a why ๐Ÿ˜‰

dim spindle
#

but it IS showing the coords of the raycast correctly

#

so i doubt thats the issue

#

would still be good to change for compatibility

leaden ice
dim spindle
#

yeah no its returning the correct value for the ray position

leaden ice
#

ray.GetPoint(0f) is just the origin of the ray

#

which will always be the same

#

no matter what mouse position you plugged in

#

it's just the camera's position

#

I think it could be the mouse thing still

dim spindle
#

yeah

#

but isnt it ray to screen point

#

meaning

leaden ice
#

yes

#

The ray starts at the camera position

dim spindle
#

ohh nvm i get it now im just bad at thinking

#

yeah

#

i have 0 braincells and i should quit gamedev ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘

#

jk

leaden ice
#

try it and lmk

dim spindle
#

i dont wanna try quitting gamdev!!!!

#

BTW

#

how can i replace Input.GetAxisRaw("Mouse Y")

#

and the other one

#

with new input system so i never use both anymore

leaden ice
#

Mouse.current.delta.ReadValue().y

dim spindle
#

thank you

#

i can also just shorten it Vector2 mouse_delta = Mouse.current.delta.ReadValue();

#

very nice

#

only downside is it goes HYPERSPEED compared to the old one

#

very weird

#

i will just apply a fixed multiplier ig for now

arctic ingot
#

All I can go off of is that it happened after I put the same object in both the viewport and content section of the Scroll Rect, it happens no matter the unity version, and it crashes every time I open the scene

#

I looked at the scene inside a text editor and it looks fine so I doubt the scene itself is corrupted

leaden ice
dim spindle
#

i dont see it but i AM skimming

#

so

#
void mouse_look()
{
    Vector2 mouse_delta = Mouse.current.delta.ReadValue();
    Vector2 raw_frame_velocity = Vector2.Scale(mouse_delta, Vector2.one * menu_handler.look_sensitivity * player_camera_control_adjustment);

    frame_velocity = Vector2.Lerp(frame_velocity, raw_frame_velocity, 1 / smoothing);
    flash_frame_velocity = Vector2.Lerp(flash_frame_velocity, raw_frame_velocity, 1 / flashlight_smoothing);
    look_velocity += frame_velocity;
    flash_look_velocity += flash_frame_velocity;
    look_velocity.y = Mathf.Clamp(look_velocity.y, -90, 90);
    flash_look_velocity.y = Mathf.Clamp(flash_look_velocity.y, -90, 90);

    player_transform.rotation = Quaternion.AngleAxis(look_velocity.x, Vector3.up);
    camera_transform.rotation = Quaternion.AngleAxis(look_velocity.x, Vector3.up) * Quaternion.AngleAxis(-look_velocity.y, Vector3.right);
    flashlight_controller.Move_Flashlight(Quaternion.AngleAxis(flash_look_velocity.x, Vector3.up) * Quaternion.AngleAxis(flash_look_velocity.y, Vector3.right));
}
#

discord be like

#

"what is text formatting?"

#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

dim spindle
#

even this isnt doing it

#

smh

#

ok andddd

#

it does not work

timid moon
#

EditorWindow - What is called when I move/create a new window?

dim spindle
#

still

leaden ice
#

hard to judge what's up

dim spindle
#

fair enough

#

but tested on a lower framerate system (the linux system that wont raycast correctly djfsklfjasf) and it didnt scale weirdly after my multiplier

#

so i think we are good

#

anyways

#

raycast issue still stands

#

this is weird

#

im gonna try setting some sort of reference point maybe and picking a point a few units down the ray

leaden ice
#

really? Could've sworn that'd be it

dim spindle
#

maybe that would provide insight

#

yeah

#

no clue

#

its real weird

#

i just turned off both mode as part of the next update im gonna try

#

any other suggestions

#

it takes a few mins to update so i dont wanna update without some bigger change

leaden ice
#

nothing I can think of

#

maybe add more logging

#

like logging mouse positions, the ray definition itself, the layermask value, inventory_grab_range, main_camera etc..

#

just dump a whole bunch of info and see what's different if anything

dim spindle
#

inventory_grab_range is a const

#

its 5f

#

main_camera is set in Awake() using Camera.main

#

but again the ray coords are teh same

#

so its 99% sure the main camear

leaden ice
dim spindle
#

none of my other cams have main cam but i can try

leaden ice
#

and in a less likely scenario - you mess with camera tags during initialization

dim spindle
#

i think ive used tags once

leaden ice
#

or maybe you instantiate the main camera?

dim spindle
#

no

leaden ice
#

Could be an order of execution issue if the main cam is instantiated

dim spindle
#

main cam is in the scene, and has a script that moves it to the client-owned player object when the scene starts

#

not other player objects

#

that would be broken

#

lol

leaden ice
#

networking is involved?

#

That's definitely a monkey wrench

dim spindle
#

yeah

#

i feel like it wouldnt affect it too much though?

#

idk

#

also there are weird cases where you CAN pick up items

#

but i havent found anything consistent yet

#

so realllllly not sure

leaden ice
arctic ingot
#

I've uh...I seem to have broky

leaden ice
#

Looks like you've got a broken scene file

dim spindle
#

and on linux it does not work as host OR as client

#

but idk maybe linux networking hates netcode

arctic ingot
dim spindle
arctic ingot
#

Not for this project

dim spindle
#

is it not a big one

#

or what

arctic ingot
#

Company security standards waaaa

leaden ice
#

Which networking framework are you using?

dim spindle
#

netcode

dim spindle
#

but

#

why on linux

#

and not windows or other windows or editor windows

arctic ingot
# arctic ingot :/

objectReference: {fileID: 2077924899, guid: 00000000000000000000000000000000, type: 0}

dim spindle
#

also what do you mean earlier by the actual definition of the ray?

leaden ice
dim spindle
#

{ray} ?

#

you can call multiple casts on the same ray right?

#

i wanna try a mock cast for debugging that doesnt have item restriction

#

like flag mask i meant

leaden ice
dim spindle
#

it is just printing rays lol

#

it looks like its working fine

#

but its not

leaden ice
# dim spindle but its not

Kind of a weird "hail mary" shot here. What happens if you run Physics.SyncTransforms(); right before the raycast

dim spindle
#

uhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

#

it just works tho

#

but like

#

only sometimes

#

the raycast hit an item, and when i went to try those coords from the log

#

it worked on the windows version

#

so the coords and dir are correct

#

im confused lol

#

ok so it only hits my items on very specific areas in linux

#

will you be here tommorow i wanna go sleep rn

#

and also when the ray DOES hit, it just picks up the item as expected

#

so its something with the ray not hitting for some reason

#

alright then

#

pain\

dim spindle
red flax
#

Hi I was wondering if someone could help me,

So basically I'm trying to setup a custom editor window, to automatically select an object from my project folder to show up in the inspector, basically what normally happens if you select it normally with the mouse but I just wanted to tie it to button click, is there anyway to do that?

Quite hard to google this since you type in something along the lines of selection and inspector, and you get specifically editor related setup, Selection.gameObjects (which only works for objects in the scene not project folders).

Any help would be appreciated, thanks!

#

So this works, it didn't work for me the first time around (and also the documentation saying the object selection in the scene is misleading) because I didn't setup the path correctly but basically in order to select something from a specific folder, you'd do
UnityEngine.Object objectYouWantToSelect= AssetDatabase.LoadAssetAtPath("Assets/Project/Folder/ObjectInFolder.asset", typeof(UnityEngine.Object));
Selection.activeObject = objectYouWantToSelect;
and that does the trick!

#

okay sorry a bit more work than what I thought, but basically this is what I found https://forum.unity.com/threads/selecting-a-folder-in-the-project-via-button-in-editor-window.355357/ , I have to use the selection bit and then the ping object method call, couple of steps in between but overall it's pretty simple to setup

prime sinew
#

nice, thanks for sharing!

red flax
#

yup no problem! I setup a way to load scenes from a window, since you know it's annoying to have to shuffle through and find your scene, so what something else but for specific scriptable objects, the cool thing is having a button that auto generates the code for the buttons (good ol' automation) so once I figure out the kinks to selecting an object, it's gonna be updatable with the click of a button ๐Ÿ˜„ it's pretty cool having code generate code

median folio
#

Hello, just wondering if there is a neater way to do something like this? It stores all the different positions my blocks can go in for each level. I was thinking SO? Although it will probably be a pain to enter each of the positions into it.

simple edge
#

I agree with that, but it depends on your use case a bit, and how you structured your levels

You could've made a scriptable object containing a list of vector3s, so that each level would have its own scriptable object
But it kinda makes me wonder why you wouldn't just use different scenes at that point

latent latch
#

Those y values looking pretty precise

plucky inlet
median folio
#

Thanks all for the feedback I did feel this was messy when putting it together.

I think some form a list and calculation to determine the values would work well, I hadn't realised how similar they work so I think I might be to create a loop to generate them instead.

'level' was probably a bad word to use - it's more of a wave, Once all three waves have been completed the next level (scene) loads.

thin aurora
#

SO is only useful here if there is more logic to it

#

Even then, this is hardcoded, and a SO is more for configurable data

#

A list is the right answer here

plucky inlet
simple echo
#

hey guys! i have an 'invincibility' method for the player. so if the player collides with the enemy then they have 4 seconds of invincibility within which the enemy cannot attack the player. however, that does not seem to be working. i have attached my code for the invincibility method.

humble thistle
median folio
graceful warren
#

Hihi, so I have multiple player characters that all have different attributes such as stats. I have all the stats that a character would have as a scriptable objects. I'm currently trying to figure out how I would differentiate script-wise between the characters. Would it be with inheritance or is there another way? If I have characters inheriting from a base character script, how is that any different from not using scriptable objects?

plucky inlet
graceful warren
#

Yes

plucky inlet
#

then you already have a separation for each character, dont you? Where are you stack exactly?

graceful warren
#

If I had three characters, and in the scripts it takes the stats and does whatever, do I just need the script copy pasted three times?

rigid island
#

You need 3 scriptable objects

graceful warren
#

I do

rigid island
#

You only need 1 script

plucky inlet
#

Exactly, you just use one script on all players but they take in different SOs as a parameter. Like GameObject A,B,C all hold the "Player"Script but with different ScriptableObjects attached to them.

graceful warren
#

Hmm that was how I had it. I just wasnt sure if that was going to cause issues

rigid island
plucky inlet
#

As long as you do not share any other static values between those scripts. But again, it depends on your setup. If you add fancy systems to it, it will surely cause issues you can solve. thats dev life ๐Ÿ˜‰

graceful warren
#

I didn't really have an issue

#

I just didn't know if there was another way to do it

rigid island
#

there is many ways to do many things, but SO is a good modular way to do it

plucky inlet
#

Usually there are always multiple ways for one solution, but it always depends on the situation. Just test around, come here if you want help or suggestions, prototype system ideas and so on ๐Ÿ™‚

plucky inlet
# graceful warren ty ๐Ÿ‘

But I wont be tired to tell, if you use scriptbale objects, they will NOT persist their updated values in runtime. So if you think, your ScriptableObject is an easy way to save player stats over multiple runtimes, it wont. you have to store the scriptable objects state when you leave the game and overwrite it when starting the game. Just one thing to be sure about in SO handling

graceful warren
#

Good tell, I don't think the way I want to use the SOs involves changing their values but instead getting something from their values and changing that

#

like uhh

#

A stat such as constitution, it converts into health and instead of messing with the stat itself I just mess with the health

plucky inlet
#

Just wanted to warn you, cause I learned it the hard way back then ๐Ÿ˜„

graceful warren
#

I will keep that in my mind

rigid island
#

I try not to make anything in SO public without it

#

[SerializeField] private int moveSpeed; public int MoveSpeed => moveSpeed;

plucky inlet
# rigid island hehe use props!

Not sure what you mean. It still will not save the values if you restart runtime, or dont I understand what you mean ๐Ÿ˜„

rigid island
rigid island
plucky inlet
rigid island
#

so yeah good tip you gave there for that one!

plucky inlet
graceful warren
#

So if I wanted to change the stats on the SO I'd want to use something else?

#

Like if they level up or something of that sort?

plucky inlet
latent latch
#

You can have different SOs per level if you wish, but ultimately they should only serve as a base template of the stats

deft pebble
#

Hey, I'm working on adding 3d object preview in UI through RenderTexture, so I have to position camera and object in the world. Are there any good practices of doing that? And if I'll need to render multiple objects with multiple cameras at the same time, how should I position them?

graceful warren
plucky inlet
# graceful warren So what would be the alternative?

A default class that you override with a database for example. The ScriptableObject system is useful for making pre defined things like classes, enemies, levels, items and so on. If you want to update those, you always have to detach the updated data from it. But that goes for a default class too. Detach it to a database, a file, a json whatever

latent latch
#

Honestly, it's probably fine to just put all the stat levels in the SOs. Maybe have a list of SOs, and you'd read each one accordingly everytime you level.

#

Or, a single SO per hero with a list of stats they have at each of their levels.

plucky inlet
#

But that way you would limit yourself to predefined values. If thats what he wants, sure can work then

graceful warren
#

No I don't want anything predefined

latent latch
#

Yeah, if you're starting out, which they are, I think that's preferable.

graceful warren
latent latch
#

Once you get the hang of serializing your data from and to then it's less of a problem.

humble thistle
#

I feel like I'm being stupid.
With the new input system (Using Unity events e.g callbacks).
How in the world do I figure out if the player is holding a key..

plucky inlet
humble thistle
#

I have but I'm also tired so that's what I said I feel like I'm being stupid

#

I'm looking at the interaction part of the docs rn but I can't find the function for Hold interaction Thonk

plucky inlet
#

If you are tired, you might just wanna take a break?

humble thistle
#

I was being stubborn and was trying to do it in the callback system

stoic plume
#

Hi!

Does anyone know how to play a sound when you interact with an NPC? I've set up an Box Collider next to them and a Sound, but I am struggling to find a script/code when key "E" is pressed that they play a sound saying ex "Hello!". Anyone know how to code it?

stoic plume
plucky inlet
swift falcon
#

Hello, I want to save my data on to a database, i haven't picked the data base because I dont know which database will be the one I need, I need my database to be able to do this:

  • assume that you have 50 players and you want to save each of their names, scores and Profile pictures...
    I want a database that saves even the profile pictures.... can anyone help me by telling me which database i need to use?
plucky inlet
swift falcon
#

the important part if I keep them locally is to also keep the pictures

plucky inlet
swift falcon
#

browse for them

#

and of course if there's a saved database, load them in the beginning

plucky inlet
swift falcon
plucky inlet
swift falcon
swift falcon
plucky inlet
#

so you would have to use string values to create those images, which would be base64 strings

swift falcon
#

so I need to save the pictures in the resources folder for example? @plucky inlet and the database will load them right?

#

you know what... i will do it the old fashioned way

plucky inlet
swift falcon
stone widget
#

How would I go about making a save system for my game? It auto saves every X minutes and can be manually saved. and when you open the game and hit play, it loads the last saved level at the last saved position.

swift falcon
plucky inlet
stone widget
plucky inlet
# stone widget I have no idea how to save or load progress.

Saving progress is basically saving values that represent the progress. thats something you should think about tho. So, for example. position of the player, experience of the player, inventory of the player. maybe enemy states and so on. Only you and your game know

stone widget
#

Ok thanks!

hallow meteor
#

hey

#

i have a problem here

plucky inlet
#

how about just telling the problem

hallow meteor
hallow meteor
#

so i have this script:

#
if(Input.GetMouseButton(0))
        {
            if(PlayerStats.movingObject != null)
            {
                print("testing1");
                Ray ray = cam.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.NameToLayer("Terrain"));
                
                    print("testing");
                    PlayerStats.movingObject.transform.position = new Vector3(hit.point.x, 0.1f, hit.point.z);
                
            }
        }
#

when i move, its kinda buggy

#

why?

#

im so confused

plucky inlet
#

how do you set the moving object?

hallow meteor
plucky inlet
#

how do you set ```cs
PlayerStats.movingObject != null

hallow meteor
#

Wait lemme show u

#

The whole code

#
Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = 10f;
        mousePosition = cam.ScreenToWorldPoint(mousePosition);
        Debug.DrawRay(transform.position, mousePosition - transform.position, Color.cyan);
        if(Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if(Physics.Raycast(ray, out hit, 100))
            {
                if (PlayerStats.movingObject != null)
                {
                    PlayerStats.movingObject.transform.Find("Movement").gameObject.SetActive(false);
                    PlayerStats.movingObject = null;
                }
                if (hit.transform.GetComponent<BuildingInfo>())
                {
                    hit.transform.Find("Movement").gameObject.SetActive(true);
                    PlayerStats.movingObject = hit.transform.gameObject;
                }
                /*Debug.Log(hit.transform.name);*/
            }
        }
        if(Input.GetMouseButton(0))
        {
            if(PlayerStats.movingObject != null)
            {
                print("testing1");
                Ray ray = cam.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.NameToLayer("Terrain"));
                
                    print("testing");
                    PlayerStats.movingObject.transform.position = new Vector3(hit.point.x, 0.1f, hit.point.z);
                
            }
        }
        if(Input.GetMouseButtonUp(0))
        {
            if (PlayerStats.movingObject != null)
            {
                PlayerStats.movingObject.transform.Find("Movement").gameObject.SetActive(false);
                PlayerStats.movingObject = null;
            }
}
hallow meteor
#

The code

plucky inlet
hallow meteor
earnest gazelle
#

Pool object classes and unityengine.pool has been added since 2021?

dusk geode
#

Hey, I want to rotate a transform around the y axis slowly and with a limit. My current setup for that is something I threw together to "just work" but I need to phase it out now

if (Mathf.Abs(axisFront.transform.localEulerAngles.y) + 3f < 60 || Mathf.Abs(axisFront.transform.localEulerAngles.y) > 360 - 60 -3f) { 
            axisFront.transform.rotation = Quaternion.AngleAxis(3f * -agentController.moveAxis.x, axisFront.up) * axisFront.transform.rotation;
            axisBack.transform.rotation = Quaternion.AngleAxis(3f * agentController.moveAxis.x, axisBack.up) * axisBack.transform.rotation;
        }

What is the proper way to do this ? Its been ages ive used unity

hallow meteor
#

Does that mean if i dont stop holding mouse

#

The object will forever in Playerstats

hallow meteor
barren lava
#

Hey im having problem making coins in my game. And how do i store the number of coins even if the game is closed so when the player is bback on the bnumber of coins collected should be the same as the number of coins collected before closing the game

dusk geode
#

<@&502884371011731486>

hallow meteor
#

<@&502884371011731486>

sleek bough
#

!ban 1084592471218065510 Spam

tawny elkBOT
#

dynoSuccess Jack.#3448 was banned

civic fern
austere orbit
#

Hi, I have an interface in which Im predefining one method. In that method, I want to use GetComponentsInChildren<Button>() but to do that I have to somehow force classes that implement that interface to inherit from Monobehavior. Does anyone know how to do that?

public interface IEquipe
{
    protected abstract string EquipedText { get; }
    protected abstract string EquipText { get; }
    private void ChangeState(bool equipe, string name)
    {
        if ((!equipe && ShopData.GetInstance().IsPurchased(name)) || equipe)
        {
            string message = equipe ? EquipedText : EquipText;
            foreach (var button in GetComponentsInChildren<Button>())
            {
                if (button.tag == "PriceButton")
                    button.enabled = !equipe;
            }
            foreach (var text in GetComponentsInChildren<TextMeshProUGUI>())
            {
                if (text.name == "PriceText")
                    text.text = message;
            }
        }
    }
}
hallow meteor
dusk geode
granite nimbus
#

what is Allocator.AudioKernel? Docs say it's "Allocation associated with a DSPGraph audio kernel." but this doesn't tell anything to me

eager citrus
#

in this script i am trying to make a shotgun that has a fire rate ad bullet spreading but it doesn't shoot

#

(the script is attached to the gun)

humble thistle
eager citrus
#

old input system

humble thistle
#

Err I haven't used the old one in so long I have no idea if that could be the problem

nimble salmon
#

I'm trying to create a reusable component for a TextMeshPro with a Quad background, without having to use Canvas. The main goal is to create these programmatically, but it's also nice to see a preview in the editor. I had to use playModeStateChanged to avoid the generated quad GameObject persisting after leaving play mode. Is this reasonable at all, or am I doing something wrong?

https://gist.github.com/vittorioromeo/036b391c5cc928f8f7a73c4c70f19396

leaden ice
proven plume
#

AudioKernel

steady granite
#

Hi, has anyone used Integrated App Purchases? I want to set an item to 0 cost but the editor wont accept it for android (apple has a free tier)

#

setting the Price to 0 or 0,00 just empties the box

dusk geode
#

Im trying to simulate a rotating axle like this. To do this ive set up an empty game object as the axle root and connected two children to it at the end points. When I rotate the parent of them this gives the desired behaviour. Im however, not sure how to do this in code ? I want a hard limit to the rotation, e.g it cant turn more than 30 degrees in either direction.

Quaternion targetFront = Quaternion.AngleAxis(-steeringParameters.axisMaximumDisplacement, axisFront.up);
        Quaternion targetBack = Quaternion.AngleAxis(steeringParameters.axisMaximumDisplacement, axisBack.up);
        Quaternion nextFront = Quaternion.Lerp(axisFront.transform.localRotation, targetFront, Time.fixedDeltaTime * agentController.moveAxis.x);
        Quaternion nextBack = Quaternion.Lerp(axisBack.transform.localRotation, targetBack, Time.fixedDeltaTime * agentController.moveAxis.x);

        axisFront.transform.localRotation = nextFront;
        axisFront.transform.localRotation = nextBack;

Im not quite sure how to do this -- ive tried using Quaternion.AngleAxis but this is wrong and I cant quite figure out why :)

leaden ice
dusk geode
#

Right, since its a local rotation around a single axis i wont have trouble with gimbal lock

#

thanks!

hard sparrow
#

Is this right?

    {
        get { return currentShield; }
        protected set { currentShield = currentShield + value < 0 ? 0 : value; }
    }```
leaden ice
#

You need to use a separate backing field

#

private int _currentShield; for example.

Your current code recursively calls the property.

dense rock
#

How do I override the operator for >= or <= for a class? Is this even possible?

tepid river
#

yes it is

#

you can overwrite everything in c

dense rock
#

i can't find it on the internet, can only find == or !=

#

Is this a good way to do it? Does this work for >= as well? Or would I need to define the == or the >= operator seperately?

public static bool operator >(Timestamp time)
    {
        if(this.hour > time.hour || this.hour == time.hour && this.minute > time.minute)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
craggy veldt
neat citrus
#

Hi, how can I "unlink" the wheels from the car body so that the suspension doesn't work like this:
this is what I have:
https://youtu.be/TyiHciltZfk
but this
https://youtu.be/CdPYlj5uZeI?t=729

A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy

~ More from Toyful Games ~

โ–ถ Play video
knotty sun
honest sky
#

im confused, what does <T> mean

oblique badger
#

Can someone help, I don't know what the issue is on this code.

plucky inlet
#

<T> is a generic parameter that helps to create generic functions where you can pass in different types

honest sky
#

as in what does it do wrong

fleet vault
#

I'm trying to build my project for iOS and the iOS resolver comes up and says
"Failed to install CocoaPods for the current user.
It will not be possible to install Cocoapods in the generated Xcode project which will result in link errors when building your application.
For more information see:
https://guides.cocoapods.org/using/getting-started.html
'gem install cocoapods --user-install' failed with code (1):
Building native extensions. This could take a while...
WARNING: You don't have /Users/XXX/.gem/ruby/2.6.0/bin in your PATH,
gem executables will not run."
I've read as much as I can find on various forums about this specific issue and tried to follow the advice but cannot fix the problem. Partially, I think it's possible I am making a dumb error when following the advice because admittedly, I'm not so familiar with package managers, dependency managers, etc., so unless it is fully spelled out for me what to do I could be following advice wrong. if anyone has an understanding of what this error likely is (maybe you have encountered it yourself) I would really appreciate your help. also, I see that under Assets>Mobile Dependency Resolver>iOS Resolver>Settings, I can uncheck things such as "Use shell to execute cocoapod tool" and "auto install cocoapod tools in editor" but I have not seen any advice regarding this settings panel. should I do something there?

plucky inlet
oblique badger
#

Shouldn't be any problem but there is

honest sky
oblique badger
#

No issues, debug.log passed all, made it in a way that the list of gameobjects that I get the gameobject position from is atleast 50 generated but yet its not working

dusky abyss
plucky inlet
#

Like each gear has a list of connected gears and their torque forces on "this" gear

leaden ice
plucky inlet
modest radish
#

Hi everyone. I'm trying to lit sprites differently, while keeping them in the same Sorting Layer (so that transparency sort mode works as I intend). I'm using URP, but apparently I don't have Light Layers available.
If there's no workaround, is there a way use Custom Axis transparency sort mode to have sprites behave like they're in the same Sorting Layer?

modest radish
granite nimbus
granite nimbus
#

but why it's formatted in different way than whole Unity docs?

leaden ice
#

All packages have separate sites like this

granite nimbus
hard sparrow
#

If you refer to a private variable in a method, and then pass that method as an Action to some other class, will that class be able to invoke the method?

#

Or how does that work

ionic cave
#

do you mean having something like public void Something(float floatNum){ floatNum += 1.0f) then calling private float aCoolFloat; Something(aCoolFloat)?

#

or do you have some example code i can look at

hard sparrow
#

In this case I'm modifying a private variable by another private variable. But I want to pass the method to another class (DelayedTrigger) which handles delayed triggers (since I want this method to be used after a certain number of rounds). And I want DelayedTrigger to be able to handle any kind of trigger, ideally

cosmic rain
ionic cave
#

I would need to see the code to get what you mean

cosmic rain
hard sparrow
#

Oh, so invoking the method is the same as using it in it's original place? So it can modify private variables and etc

cosmic rain
#

But, yeah, without an example, it's hard to understand what you're talking about.

ionic cave
#

just post a hastebin or something

cosmic rain
hard sparrow
kind wolf
#

how do i display big numbers without decimal points or scientific notations?

#

ive tried toString but it doesnt change anything

swift falcon
#

Hello

pearl radish
#

Oh no no, you ain't general fella

swift falcon
#

ah

#

wat

ionic cave
#

@kind wolf I think its .ToString("F2") or something like that for 2 decimal points

kind wolf
#

i dont want any decimal points tho

ionic cave
#

then ("F0")

leaden ice
#
myFloat:D``` to show without any decimal places
hexed pecan
#

:D

leaden ice
#

yes

kind wolf
#

it gives me an error

leaden ice
#

sorry apparently the x:D syntax is only available in string interpolation

leaden ice
kind wolf
desert shard
#

massText.text = $"{mass:D}"

leaden ice
#

Oh yeah it's F0 indeed

desert shard
#

or just use F0 as you had previously

leaden ice
#

Apparently D is only supported by integral types. TIL

kind wolf
#

same error

leaden ice
leaden ice
ionic cave
#

just do ToString("F0")

#

holy moly

kind wolf
desert shard
#

massText.text = $"{mass:F0}"
massText.text = mass.ToString("F0");

Pick one

kind wolf
#

oh those are the same thing

dim spindle
#

@leaden ice btw Physics.SyncTransforms or whatever did not work

#

sooooooooooooooooooooo\

#

ig its doomed

#

what is that question mark for @leaden ice sorry for ping again i just assume you left lol

leaden ice
dim spindle
leaden ice
#

Yes I remember now the shrug is "idk"

dim spindle
#

well i guess im doomed

uneven dagger
#

Anyone know why this only shows up when i try to build my game? its having a problem with using UnityEditor.Animations;

leaden ice
#

notice the UnityEditor namespace

#

that's ๐Ÿšซ

uneven dagger
# leaden ice YOu're trying to use editor only code in a build

Ah, im new so forgive me if its a dumb idea on how I did it. I have an array of animatorcontrollers each having a different animation. When the game starts it takes the selected one and basically equips it. If I remove that then it just underlines everything in visual studio. Any alternative ways I can research or lookup instead of doing what I did?

leaden ice
uneven dagger
#

Player buys a skin for cat and then equips it when the game starts the cat has a different animation based on what was bought and equipped

uneven dagger
#

Alrighty ill readup on it i appreciate the advice

sturdy fulcrum
#

oes anybody know how to upload a Vroid model to unity

swift falcon
#

i have a MutationStat class and a MutationSO scriptable object class that just stores a MutationStat and another value
i have a constructor that takes in the scriptable object: ```public MutationStat(MutationSO mutationSO)
{
stat = mutationSO.mutationStat.stat;
negative = mutationSO.mutationStat.negative;
canBeNegative = mutationSO.mutationStat.canBeNegative;
unscalingWithRarity = mutationSO.mutationStat.unscalingWithRarity;
mutationTarget = mutationSO.mutationStat.mutationTarget;
modType = mutationSO.mutationStat.modType;
}

then i get a list of the scriptable objects and make a new MutationStat```List<MutationSO> SOList = new List<MutationSO>(MutationSODBService.GetAllMutationStatSO());

for (int i = 0; i < SOList.Count; i++)
{
    MutationStat mutationStat = new(SOList[i]);
...
}

for some reason this ends up with the base scriptable objects being modified, anyone have any idea why that might be happening?

#

before & after

leaden ice
#

But all you're doing in the code you shared is passing references to your SOs around

#

if you think you're making copies of the SOs, you're not.

swift falcon
#

thought i was making a new one with MutationStat mutationStat = new(SOList[i]); ?

leaden ice
#

That's making a new MutationStat

#

not a new MutationSO

#

For this stuff:

stat = mutationSO.mutationStat.stat;```
You'd have to explain what those fields are
#

they are probably reference types

swift falcon
#
public class MutationStat
{
    public Stat stat;
    public bool negative;
    public bool canBeNegative = true;
    public bool unscalingWithRarity;
    public int mutationTarget;
    public StatModType modType;

    public MutationStat(MutationSO mutationSO)
    {
        stat = mutationSO.mutationStat.stat;
        negative = mutationSO.mutationStat.negative;
        canBeNegative = mutationSO.mutationStat.canBeNegative;
        unscalingWithRarity = mutationSO.mutationStat.unscalingWithRarity;
        mutationTarget = mutationSO.mutationStat.mutationTarget;
        modType = mutationSO.mutationStat.modType;
    }
}
leaden ice
swift falcon
#
        {
            MutationStat mutationStat = new(SOList[i]);
            int weight = CalculateWeight(SOList[i]);

            if (!mutationStat.negative)
            {
                positiveMutationStatList.Add(mutationStat, weight);
                if (mutationStat.canBeNegative)
                {
                    mutationStat.stat.SetBaseValue(-mutationStat.stat.Value / 2);
                    mutationStat.negative = true;
                    negativeMutationStatList.Add(mutationStat, weight);
                }
            }
            else
            {
                negativeMutationStatList.Add(mutationStat, weight);
            }
        }```
leaden ice
#

Can you share the code for Stat

#

it's probably a class

#

meaning your MutationStat and MutiationSO both share a reference to the same Stat object when you do this:
stat = mutationSO.mutationStat.stat;

swift falcon
#

it's a class which holds a double value and a list of modifiers

leaden ice
#

so modifying one is visible in both

swift falcon
#

ohhh

#

you're right

leaden ice
#

you'd need to make a new copy of it in the constructor for MutationStat to make them independent

swift falcon
#

yep that did the trick, forgot that lol, ty a bunch

stuck lotus
#

hello i am trying to create my own asset pack to host on github and i am getting close, only issue is that i cant seem to find a reference to reference to "UnityEngine.CoreModule" so its giving me issues with some transform stuff.

https://paste.ofcode.org/epAqsdMJYBwfPAuDMja3Dy

leaden ice
#

you shouldn't need an explicit CoreModule reference

stuck lotus
daring nymph
#

any DOTween users? It's a bit annoying that DOKill is not chainable, because this would have been much shorter if it was. or is there a better way to do hover animation?

public void OnPointerEnter(PointerEventData eventData)
{
    transform.DOKill();
    transform.DOScale(1.1f, .16f).SetEase(curve);

    text.DOKill();
    text.DOColor(hoverColor, .16f).SetEase(curve);
}

public void OnPointerExit(PointerEventData eventData)
{
    transform.DOKill();
    transform.DOScale(1f, .16f).SetEase(reverseCurve);

    text.DOKill();
    text.DOColor(startingColor, .16f).SetEase(reverseCurve);
}
stuck lotus
# leaden ice what errors are you getting

Packages\DungeonForge\Runtime\PcgScripts\EditorSideScripts\PCGManager.cs(302,51): error CS1061: 'Transform' does not contain a definition for 'AddComponent' and no accessible extension method 'AddComponent' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)

leaden ice
#

this is just a run of the mill "you wrote code that doesn't compile" issue

#

Only GameObject has AddComponent

#

Component / Transform do not

stuck lotus
leaden ice
#

Does not and has not ever compiled in Unity

#

but this does

thick socket
#
public enum IconTypes
{
    Gems,
    Hearts,
    Coins,
    WoodChestKey,
    GoldChestKey,
    DiamondChestKey,
    HeroChestKey,
    DuplicateHeroShards,
    RandomHeroShards,
    Xp
}

I want to create a dictionary with each type with an int of 0...whats the best way to do this?

#

can't figure out how to do it with a foreach loop

leaden ice
stuck lotus
#

this does compile fine

leaden ice
stuck lotus
leaden ice
thick socket
leaden ice
#
public int GetGems(IconTypes it) {
  dict.TryGetValue(it, out int result);
  return result;
}```
#

0 is the default value for int so this will just work.

thick socket
#

reguardless, I like the loot/feel of pre-populating the values....so Im going to

#

is there an easy way to do it for each enum ๐Ÿ˜„

stuck lotus
thick socket
#

couldn't figure out a way to get the output as IconTypes."insertname"

#

seems to just return name as string or int

#

which isn't of the Enum type

leaden ice
#

or this example from that article seems to just do it too:

foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))
{
  Console.ForegroundColor = color;
  Console.WriteLine($"Foreground color set to {color}");
}```
simple egret
#

If you can, now there's the generic version of this method available

#

Enum.GetValues<T> returns T[]

leaden ice
#

ooh yeah def use that if it's available^

thick socket
#
foreach (IconTypes icon in Enum.GetValues(typeof(IconTypes)))
        {
            ConsumableList.Add(icon, 0);
        }
#

this works great thanks ๐Ÿ™‚

idle flax
#

Hey, got a quick question. I have a float that ranges from -40 to 150. How do I convert that float to a number between 0.0 to 1.0?

civic fern
#

guys i just did a lot of stuff in play mode is it possible to save everything i just did without losing it when i exit play mode

dim spindle
#

Ok im gonna ask again, because I really want this to work. Is there any reason a raycast would work differently on windows VS. linux? I have a system that im trying to make to pick up items in my game, for some reason, when I make a raycast at the exact same position (as in "Ray Created: Origin: (401.40, 3.38, 420.94), Dir: (-0.15, -0.37, 0.92)"), it works on two different windows machines, and my editor, but not on linux. any reason why?

idle flax
dim spindle
#

btw my ray IS still hitting stuff

#

just not what i expect

#

if i cast the same ray beforehand without filtering, it hits stuff, just never hitting the item that im trying to grab

#

maybe there is a way to render a ray in the game?

#

that would be useful for debugging

solemn raven
#

hi ,
could someone explain to me what im doing wrong in a simple math equation ?

float initial = 0;
float final = 0 ;
float additional = 5;

final = initial - additional;
/// final is always = 0
// expected value for finale = -5;

does the above equation make sense ? or did i do something wrong else where ?

maiden breach
dim spindle
#

for example how you are checking the value of final

#

did you Debug.Log it

leaden ice
solemn raven
simple egret
#

Looks good to me, C# hasn't lost its mind yet

leaden ice
#

show your real code ๐Ÿ˜‰ @solemn raven because something else is going on here.

dim spindle
#

can you show how you printed them

civic fern
#

do you guys have your animations code all in a seperate script or do you leave it in ur movement script

dim spindle
# dim spindle Ok im gonna ask again, because I really want this to work. Is there any reason a...

btw for the 3rd(?) time now here is the code for this

public void Pickup_Pressed(InputAction.CallbackContext ctx)
{
    Debug.Log($"Pickup Press: {ctx.performed}");
    if (!ctx.performed)
        return;

    RaycastHit hit;
    Ray ray = main_camera.ScreenPointToRay(Mouse.current.position.ReadValue());

    Debug.Log($"Ray Created: {ray.GetPoint(0f)}, {ray}");

    Physics.SyncTransforms();
    if (Physics.Raycast(ray, out hit))
    {
        Debug.Log($"[Test] Ray Hit An Object: {hit.transform.gameObject.name}");
    }

    Physics.SyncTransforms();
    if (Physics.Raycast(ray, out hit, inventory_grab_range, mask)) // Do a Raycast with only layer 8 (Items)
    {
        Debug.Log($"Ray Hit An Object: {hit.transform.gameObject.name}");
        Transform hit_transform = hit.transform;
        GrabItem(hit_transform.gameObject);
    }

    Debug.Log("Cast Attempts Done.");
}
#

the first print always runs

#

and the second one

#

and the third one

#

but not the fourth

stuck lotus
dim spindle
#

also that Physics.SyncTransforms() call is added as a debugging measure as suggested by someone here

#

if you are wondering about it

#

but I havent figured out any reason that this shouldnt work

solemn raven
dim spindle
#

its like the hitbox on my items just is smaller with linux but that makes actually no sense

#

and SOMETIMES i do hit the item

#

just 99% of the time not

wintry schooner
#

I have a transform hierarchy like so: Parent - Child - ChildChild. When I call ChildChildTransform.Rotate(vector.right, someAmount); everything works as expected, until the Child object also rotates. At that point, my ChildChild object accumulates errors and wobbles around a little (as seen by random values popping up in the y and z axes in the inspector). They can get large enough to be perceptible, which is no good.
To be clear, the Child object basically does the same thing, only it rotates around Y (and is obviously doing just fine).
Any clues as to what could be causing this and how to fix it?

wintry schooner
#

2 independently rotating axes, essentially

leaden ice
#

for what

#

what is this

#

FPS controller?

wintry schooner
#

A turret

leaden ice
#

something else?

#

Keep your own yaw and pitch floats

#

rotate the objects with transform.localRotation = Quaternion.Euler(0, yaw, 0) and likewise for the pitch on the other object

wintry schooner
#

Hmmmm.

#

Could work... let me think, quite a few things to consider with that ๐Ÿค”

#

Yea, that could work. That potentially has quite a few implications on the rest of my code, but might just be fine. Thanks, I'll see where that leads. Still, curious why that's happening. Any idea?

molten sandal
#

Hi there

#

I would like to ask an advice

#

I have this code

#
void Update()
{
    // Move Forward
    if (Input.GetKeyDown(KeyCode.W))
        moveForward = true;
    if (Input.GetKeyUp(KeyCode.W))
        moveForward = false;
}

private void FixedUpdate()
{
    CalculateThrustForce();
}

private void CalculateThrustForce()
{
    float maxThrust = maxForwardThrust;
    float timeToMaxSpeed = topForwardSpeedTime;

    if (moveForward)
    {
        thrustAcceleration += Time.fixedDeltaTime;
        if (thrustAcceleration > topForwardSpeedTime)
            thrustAcceleration = topForwardSpeedTime;
    }

    if (moveBackwards)
    {
        thrustAcceleration -= Time.fixedDeltaTime;
        if (thrustAcceleration < -topBackwardSpeedTime)
            thrustAcceleration = -topBackwardSpeedTime;
        maxThrust = maxReverseThrust;
        timeToMaxSpeed = topBackwardSpeedTime;
    }

    if (!moveForward && !moveBackwards)
    {
        if (thrustAcceleration > 0)
        {
            thrustAcceleration -= Time.fixedDeltaTime;
            if (thrustAcceleration < 0)
                thrustAcceleration = 0f;
        }
        else
        {
            thrustAcceleration += Time.fixedDeltaTime;
            if (thrustAcceleration > 0)
                thrustAcceleration = 0f;
        }
    }

    float thrust = Mathf.Lerp(0, maxThrust, Mathf.Abs(thrustAcceleration) / timeToMaxSpeed);
    rb.AddRelativeForce(new Vector3(0, 0, thrust * Mathf.Sign(thrustAcceleration)) * thrustMultiplier, ForceMode.Acceleration);
}
#

Any suggestion to make that code simpler and cleaner?

wintry schooner
#

First of all, use input axes rather than KeyDown and KeyUp

#

Then multiply those with your thrust and whatnot, rather than doing booleans

molten sandal
jaunty sleet
#

Does anyone know how I could draw a custom display in a unity editor I am making? I want to make a window with a scroll bar and draw lines inside it, etc for my level editor

#

is there something kind of equivalent to a drawing panel I can use? I'm sure you guys have used something like I have when you were learning where you can code to draw shapes, etc on a panel. I'd like to use something like that

molten sandal
wintry schooner
#

Yup

molten sandal
#

kk

molten sandal
#

I need some help here please

#
private void CalculateThrustForce()
    {
        float thrust = Input.GetAxis("Thrust");
        float thrustDir = Mathf.Sign(thrust);

        thrustAcceleration += (Time.fixedDeltaTime * thrustDir);
        thrustAcceleration = Mathf.Clamp01(thrustAcceleration);

        float thrustAmount = Mathf.Lerp(0, maxThrust * thrust, Mathf.Abs(thrustAcceleration) / thrustTime);
        rb.AddRelativeForce(new Vector3(0, 0, thrustAmount * thrustDir) * thrustMultiplier, ForceMode.Acceleration);
    }```
#

Canยดt figure out how to apply fore forward or backwards

#

At this line ```haskell
rb.AddRelativeForce(new Vector3(0, 0, thrustAmount * thrustDir) * thrustMultiplier, ForceMode.Acceleration);

molten sandal
#

Because that's in world coordinates

#

I need to apply the force in local space

somber nacelle
#

AddRelativeForce applies it in local space which is basically the equivalent of AddForce

#

but surely the "thrustDir" variable determines whether the thrust is forward or backwards

molten sandal
#

If I use AddForce, the force is applied incorrectly

somber nacelle
#

so there shouldn't be anything special you need to do to "add force forward or backwards"

#

although you are doing some weird calculations with the thrust variable then multiplying it by its sign without first taking the absolute value of the calculations

#

which of course means when you multiply the negative number by the negative 1 for its sign it suddenly becomes positive ๐Ÿ˜‰

molten sandal
#

Yeah, I am kind of failing there

#

I see the issue

#

I am clamping between 0 and 1

#

I need to clamp between -1 and 1

somber nacelle
#

i mean that's not the only issue

#

you need to either stop mutliplying by thrustDir or you need to take the absolute value of thrust before doing any of the other calculations

molten sandal
#

Let me explain you what I am trying to get here, I think that will be easier

somber nacelle
#

you don't need to explain, you are only providing a positive value no matter what because of the multiplications by -1 when the value is negative

molten sandal
#

can you show me which line is wrong?

somber nacelle
#

my dude what do you think a negative number multiplied by -1 ends up being?

molten sandal
#

sorry lol, I am very mentally tired rn

somber nacelle
#

then take a break and come back to it with a fresh mind

warm night
#

Hey, i have an animator, with an animator state, which moves the transform of my gameObject. However, this animator state is never called, by transition with triggers, or something like that, but, my gameobject has his positions completely frozen, i cannot move it, can someone help me? :/

thick socket
warm night
#

ok, i have this animator :

#

The "SwitchPhase" animator state contains the motion which moves the transform of the gameobject

#

but the transition from emptyState to SwitchPhase, is never called

#

i debug.log the code and check , and never called

thick socket
warm night
#

sorry, didn't see the channel, mb

thick socket
#

all good

#

kept waiting to see code ๐Ÿ˜„

grizzled needle
#

Does a struct return a copy of itself or a reference when used as a property { get; private set: }?

grizzled needle
lucid valley
#

I don't think the Unity C# version has access to ref fields

lucid valley
grizzled needle
#

If I use it as a class, then it would be open to change public variables within

lucid valley
#

or just remember to set the variable back after you change it, don't make it private set

grizzled needle
#

I want the public variables inside to be protected instead of just the parent class/struct

leaden ice
#

I don't see what struct vs class has to do with that

lucid valley
grizzled needle
#

Ill explain in 1 sec

grizzled needle
leaden ice
grizzled needle
#

I have a struct that holds a bunch of parameter variables for a director/manager class, the structs are presented as a variable in my director class that are exposed as private set properties so that I can read these variable at anytime while also having them change as i need them from within the director class

#

A struct works perfectly for my needs, the only problem is that i want to access these variables without forcing a copy of them every single time I need to

leaden ice
#

What's a "struct class"

grizzled needle
#

Real

leaden ice
#

What are you gaining by using structs here exactly that you don't want to give up?

grizzled needle
#

I have two groups of variables that I need constant global access to, like static variables, but they need to be changed exclusively by the director class and nothing else

leaden ice
#

Three options for that:

  • When you want a "view only copy" of your object create and return a fresh copy, not the original.
  • Make your class implement an interface that presents its data through read-only properties. Return your object as that interface instead of the concrete type when asking for the view-only copy.
  • Make your class contain a struct. Pass the whole class reference when you want to be able to modify it. Pass around only the struct (copy) when you want just a view.
grizzled needle
#

Ah, an interface for the struct is probably what Im looking for

leaden ice
grizzled needle
#

If i typecast a struct into an interface, does it still create a copy of that struct?

#

Or can i do (IStructVar)(ref structVar)

leaden ice
#

The point is to use this in conjunction with a class not a struct

#

so you know you have a reference not a copy

stable rivet
#

I have a CardEntity that is created from a CardModel SO whenever a card comes into play (e.g. added into your deck). I'm now getting around to writing methods to render the card on screen, control its animations, interactions with the user, et cetera.

In previous games, I've sort of just stuffed everything inside MonoBehaviours with no real separation of concerns. I'd like to get out of that habit, but I'm struggling to figure out the soundest way to design this. My first instict is to create a separate UICardController that would live on a prefab, and have a method that lives on a factory class somewhere to create an instance and return the UICardController. I'm in doubt on if that's a solid approach though, and wanted to see if anyone had any wisdom to share ๐Ÿ™‚

grizzled needle
dim spindle
remote lion
#

Hello there, i have been wandering and searching for an answer but i can't find it, so i'm here to ask if it's good practice to use the method "Sigletoon" to change scenes or levels or is there a better way to doit.

hexed pecan
hexed pecan
stable rivet
remote lion
velvet quartz
#
        {
            _enemyList.Remove(go);
            PlayerUI.Instance.SetZombieRemainingText(_enemyList.Count);
        }

We dont need to check for contains ? So we forget about it and remove directly ?

velvet quartz
#

Euh ok but what that will change ?

#

_enemyList.Remove(go); will not occur a bug if the go don't exist on the list

somber nacelle
#

correct, because it just returns false instead of throwing an error you don't need to check if the item is in the list before removing it

velvet quartz
#

So for performance we don't do the check

somber nacelle
#

unless you need to know whether the item is in the list for some other logic, then you do not need to do that check

velvet quartz
#

ok ty.

fiery saddle
#

I have WebGL game. Iam trying to save game with playerprefs and storing string of JSON. My Weapon class has Sprite icon which it gets from ScriptableObject who has reference to the sprite. How can I save and load sprite with JSON? I saw Resources folder which really messes up my structure of files. I saw storing sprite into raw texture and will be my next attempt but I would really like to hear if there is better way?

Also if somebody has better idea to save progress? I would really like to hear it. If playerprefs becomes problem and can't store so much info I think ill store files at persistentDataPath

lost dove
#
            var text = gameObject.AddComponent<TextMeshPro>();

Variable text is null after this line, but I do not understand how.

queen mango
#

Hello
I do button for pause game
When I click it the timescale = 0 and menu show
But if I click the button behind the menu I can do that
How can I solve this?

leaden ice
queen mango
#

OK

stable rivet
leaden ice
#

just returns null from AddComponent

#

btw in general you can add duplicate components

#

but there are certain that you can't. For example Graphic and Rigidbody

#

for those - it returns null

stable rivet
#

oh right, i stand corrected

velvet quartz
#
private void SpawnZombie()
    {
        for (int i = 0; i < 32; i++)
        {
            int randomSpawnerIndex = Random.Range(0, _spawnerArray.Length);
            Vector3 spawnLocation = _spawnerArray[randomSpawnerIndex].transform.position;
            Vector3 randomPoint = new Vector3(Random.insideUnitCircle.x, 0f, Random.insideUnitCircle.y) * 5f + spawnLocation;
            if (!Physics.BoxCast(randomPoint, _pfEnemy.transform.localScale, transform.up, out RaycastHit hit, transform.rotation, 20f, _spawnLayerMask))
            {
                GameObject go = Instantiate(_pfEnemy, randomPoint, Quaternion.identity);
                _enemyList.Add(go);
                break;
            }
        }
    }

Goal is to spawn enemy on a spawner. What do you think of my script and how you will do it ?

lost dove
#

@leaden icethank you!!

slim mason
#

how can i interact with ui while my cursor is locked?

fluid lily
#

if you camera is rotating then the cursor is still in the center.

#

another option is to enable cursor movement while UI is up.

slim mason
#

ill see if i can do a ui panel sort of thing

fluid lily
#

Is there anyway to add options to that menu through extensions? I need a SwithActive() Method there, to just switch it from active to deactive, and visa versa

#

I know I could add my own component to have this functionality, but it is so basic that I would just want it everywhere.

quartz folio
#

I have no idea if extension methods appear in that list, but you could try it and see

fluid lily
#

Yeah no, which I guess I could have forseen from Unity

wide ermine
#
adsRotation = -Quaternion.LookRotation(transform.InverseTransformDirection(gun.GetSight().forward), transform.InverseTransformDirection(gun.GetSight().up)).eulerAngles;

combined with

float adsCurveValue = adsCurve.Evaluate(adsWeightLerped);

arms.localPosition = adsPosition * adsCurveValue;

aiming down sights while an animation is playing (like reload animations) makes the viewmodel go abolutely crazy

quartz folio
#

Is looks to be using assembly definitions (I imagine in the Runtime folder) can you check that that's configured correctly?

stuck lotus
quartz folio
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.

gaunt vapor
#

ah okay Sorry

rocky dirge
#

is there any way i can show a c# record obj in the inspector?

quartz folio
rocky dirge
#

i see, ty

tiny herald
#

Why cant I script ๐Ÿ’€๐Ÿ’€sadok

wide ermine
quartz folio
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.

tiny herald
quartz folio
#

Configure your IDE

rocky dirge
stable rivet
quartz folio
#

Please don't provide no-context answers to people without configured IDEs

rocky dirge
# tiny herald where

next to the script name is (line #, character #) and the following message explains it all

tiny herald
stable rivet
quartz folio
# tiny herald

Configure your IDE as you have been directed to before attempting to get an answer to this basic question

rocky dirge
#
  1. configure your ide as people said
  2. count the braces ig
tiny herald
quartz folio
#

and the command that was posted immediately after

viral cipher
#

Hello!

I am attempting to make a platformer type game for a game development class at my high school. I noticed that on the school computers, the game's physics were much floatier than on my home computer.

I was wondering how to fix the problem without changing the massive amount of code I have; re-writing it to fit the fixed update loop for ONLY the physics, and having the update loop only for inputs (since it seemed like a lot of work for the fixed update loop to just fail and go over the physics stuff twice)

#

TLDR:

I essentially have everything in an update loop, and don't want to have to reformat literally all code for every physics-influenced object

#

Extra question:

Can I technically make this work by proportionally setting the masses depending on the time seen within Time.deltatime?

rocky dirge
viral cipher
rocky dirge
viral cipher
#

I am not using Time.deltaTime, nor Time.fixedDeltaTime, no

#

so I don't think so

cosmic rain
#

You wouldn't use it for forces anyway. But they need to be applied in fixed update if you want deterministic behaviour.

#

So just move the parts where you add forces, to fixed update.

rocky dirge
#

they might be using ForceMode.Impulse or .VelocityChange tho

#

which will need to be multiplied by Time.deltaTime i think

viral cipher
#

I'm using ForceMode2D.Force

rocky dirge
cosmic rain
viral cipher
#

problem: the part where I add forces is tied to my inputs, and I don't want to sacrifice input consistency

#

pain.

cosmic rain
#

How is it tied?

#

Is it using the new input system or something?

viral cipher
#

so like, I'm using conditionals each frame to check for inputs.

#

then based on that, I add a force

cosmic rain
#

Okay..? Then just cache the input conditions and use them in fixed update.

viral cipher
#

alright

#

*pain intensifies

#

lol

viral cipher
cosmic rain
#

No. It's a terrible solution.

viral cipher
#

alright

#

fair enough

cosmic rain
#

The actual solution is very simple with a bit of refactoring.

hexed pecan
#

At least if youre polling like with GetAxis or whatever the new system uses

viral cipher
#

I'm using Input.GetAxisRaw and Input.GetButtonDown a lot

#

I'll probably just store the values of the inputs in variables for the fixed update loop to use and reset each time it updates

#

idk

#

At least thats what I got from dlich

hexed pecan
#

GetButtonDown must go to Update yeah. But if you use it to add a one-shot force (like a jump with ForceMode.Impulse), you can add the force directly in the Update function, it will get applied next physics step anyway

viral cipher
#

oh

#

so I just need to modify the force values a little bit

#

with ForceMode.Impulse

hexed pecan
#

You don't really need to modify it at all (assuming youre doing something like if(Input.GetKeyDown(jumpKey) rb.AddForce(jumpForce, ForceMode.Impulse);)

#

But continuous forces you should do in FixedUpdate

viral cipher
#

ok

cosmic rain
viral cipher
#

ngl I dont know how continuous forces are even set up

#

I'm just calling the addforce once, and thats about it

hexed pecan
#

Don't use ForceMode.Impulse with those btw

viral cipher
#

yeah I won't

#

I'm just using velocities for that

#

and, I think I definitely need to change the force value for Impulse mode

#

since I just used it, and my character jumped straight off the screen, lmao

hexed pecan
viral cipher
#

so how would I make my impulse the same as the force-mode?

#

without using Time.deltaTime?

hexed pecan
#

Never use deltaTime with forces

viral cipher
#

I understand that

hexed pecan
viral cipher
#

idk ill just mess around with some stuff

hexed pecan
#

Like around 50x smaller value

viral cipher
#

yeah

#

ok, will do. Thank you so much!

swift falcon
#

can i ask a question?

cosmic rain
#

No

swift falcon
#

womp womp

cosmic rain
#

People that say that are not allowed to ask questions

hexed pecan
viral cipher
#

lol

swift falcon
#

haha

cosmic rain
#

If you learned the lesson, go ahead and ask your question

swift falcon
#

how would you go about detecting the bottom half of a collider?

cosmic rain
hexed pecan
#

When colliding or what?

swift falcon
#

say a raycast hits the top half/bottom half with a seperation in the middle

#

to detect something like feet/torso or will i have to make seperate colliders

hexed pecan
#

You could convert the hit position to that object's local coordinates, and check its y

#

But multiple colliders would be more intuitive IMO

cosmic rain
#

Ideally, you'd make separate colliders(probably triggers) for the bones.

#

Often, if you have a ragdoll setup, you'd use the ragdoll colliders for that.

swift falcon
#

ty

if(hit.point.y > hit.transform.position.y ) {
}

this is working

#

ty

grizzled needle
#

Is there a way to typecast a SerializedProperty into a custom class like TestClass or something? Or at the very least edit its values like TestClass.value and apply it to the property through the editor using a custom editor class?

stoic plume
#

Hi!
Does anyone know why my AudioSource is being removed when I go in "Play Mode"?

somber nacelle
#

something is probably destroying it

leaden ice
#

You can also use FindPropertyRelative to get its serialized fields

stoic plume
somber nacelle
#

yours

stoic plume
#

Do you know what might be destroying it?

#

There's no "Gameobject(destroy)" hooked on any script

somber nacelle
#

considering i've not seen your project or your code i have literally no way of knowing

leaden ice
stoic plume
#

Can you please check what it is?

leaden ice
#

Different code

stoic plume
#

It's only this code

grizzled needle
leaden ice
somber nacelle
# stoic plume It's only this code

is the issue actually that the reference in the inspector is being set to null and not that the audio source itself is being destroyed?

leaden ice
quartz folio
stoic plume
#

Alright, so [SerializedField] instead of public?

somber nacelle
#

if i was right about the issue that likely isn't going to change much. you'd need to remove that line from Start since the object clearly doesn't have an AudioSource component attached to it

rocky dirge
#

u may have component ref assigned but set to null in start

stoic plume
#

All of you I should say

marble halo
#

So im trying to make ladder climbing and i have this value that determines which direction you climb in depending on where you are looking

#

the problem is, if the direction you are looking in is the center (aka 0) you stop moving

#

Is there a way to make it so that a float is never 0?

#

Mathf.Round(player.cmPosition.forward.y)

#

heres what determines where you move

#

Vector3 direction = player.transform.up * Mathf.Round(player.cmPosition.forward.y) * player.currentinputvector.y; //allows player to climb up or down depending on where they look

#

IDK how to describe it

somber nacelle
#

round it on another line, then you can use a ternary or if statement to check if the value is 0

nimble salmon
#

I really need some help understanding why my mesh with procedurally generated vertices doesn't work in prefabs. I have this setup:

  • GameObject
    • TextMeshPro
    • Quad

The GameObject has my script TextWithBackgroundController, which holds a reference to the TextMeshPro and the Quad. In its Update, it changes the Quad's vertices via quad.GetComponent<MeshFilter>().mesh.vertices in order to create a background for the TextMeshPro. This works perfectly in both play and edit mode.

Now, I'd like to make a prefab out of these three objects. When I do so, and spawn a new instance of that prefab, the mesh doesn't render at all. The debugger shows that the vertices are set correctly, but that there are no triangles.
I can fix the issue by manually going into the new Quad, and changing the mesh from "Quad" to "Quad Instance" in the mesh filter component.

I don't get it at all. Why does the prefab not render? Why does the mesh not get saved in the prefab? Why does changing the mesh manually fix the issue?

The source code for my script is here: https://gist.github.com/vittorioromeo/d500c347465f5cc3555001d00a1dd6cc

This is really driving me nuts, I don't understand this behavior at all.

velvet quartz
#
if (collision.gameObject.TryGetComponent(out IDamageable damageable))

I do this for apply damage to a target but some target are friendly and so can't damagable between then how you can know if you can damage the other target or not ?

worldly hull
#

this may be an advanced question, is there a way to know how many size that a specific API/package occupied in built app?

leaden ice
worldly hull
#

thx

nimble salmon
woeful spire
#

currently getting pissed off at the TrailRenderer for emitting even though it shouldn't be (I'm probably wrong somewhere I hope).
I wrote this as a workaround 'cause apparently the .emitting value needs one frame before it affects the trail.

private IEnumerator StupidOneFrameWaitCauseTrailRendererSucks()
    {
        trail.emitting = false;

        yield return null;

        currentAnimation = StartCoroutine(AnimateFromTo(GetIndex(), ContinueAnimation));

        yield return null;

        trail.emitting = true;
    }

This should wait a frame after disabling emitting, then teleport it, wait one more frame - then finally emit again.
What ends up happening is the code sometimes working, as the picture shows.
The dead end up top is a successful jump, while the line from the bottom to the middle was a not-so successful one. Any ideas?