#archived-code-general

1 messages · Page 426 of 1

restive canopy
#

but because i wrote this out expecting to get exactly the objects Im looking for, it makes compile errors

rigid island
#

Find is a pretty garbage method, you should never seek objects by name or string

rigid island
#

hard to spot errors if everything looks k

restive canopy
#

no

#

it isnt

rigid island
#

then why is it all white?

restive canopy
#

THIS is the compile errors

rigid island
#

you just proved my point

#

Compile errors because you're like coding without a configured IDE..

#

if you cant see what members you are able to access within a class there is no point in coding with a text editor

restive canopy
#

I went through the trouble of configuring it to unity!

rigid island
#

if that were the case it would be underlining red

restive canopy
#

oh ffs

rigid island
#

didnt we do this already

restive canopy
#

i thought i did!

rigid island
#

well then make sure it doesnt say Unloaded although that assembly is probably not related

restive canopy
#

it needs .NET Desktop for some reason

rigid island
#

huh ? where

restive canopy
#

when I try to fix the unloaded

rigid island
#

go to unity close VS, regen project file, open script from unity again

restive canopy
rigid island
# restive canopy

are you sure the Unity Workload is installed in Visual Studio installer

restive canopy
#

yes!

rigid island
#

idk what is that code assist assembly is

#

whatever it is might be causing conflicts

restive canopy
#

one second

#

running through it

#

oh boy, I had to drag the instance to the object slot manually

#

this is rubbish

#

demo of what I mean

#

how do i get it so it does the "get instanitation" automatically

rigid island
#

Awake only works if the object was created by the time that Awake runs

#

and even if the other Instantiated it at Awake its never guaranteed the order

#

at very least you'd do
Awake() Instantiate
Start() Find

restive canopy
#

PlayerBase(Clone)

rigid island
#

either way Find is still garbage and you shouldn't do it this way

restive canopy
#

instantiations is beginner?!

rigid island
#

this channel goes under the assumptions you know about the basics.

#

what you're asking is very beginner yes..

#

..I asked where you do instantiation and you wrote the name of the object lol

restive canopy
#

right

#

i thought the question was "what are you instantiating

#

im doing the instancing in a persistent gameobject

rigid island
#

already understand the setup, I just saying its not a good way because you're relying too much on Unity events

#

this is why I mentioned Instantiate returns an object and it would be wiser to use that appropriately

#

though i wonder even if subscribing to Awake would it miss the ChangeActiveScene event..

restive canopy
rigid island
restive canopy
#

cause it goes

var InstantiacingObject = Instantiate(CPU.PlayerPawns.PlayerHall);

#

no?

rigid island
#

this would not give a compile error

restive canopy
#

I put it at the start of the script with everyone else

#

and what do you know

rigid island
restive canopy
rigid island
#

mate.. you gotta put methods inside method to call them.

steady bobcat
#

yea you cant use var for a class member 😐

rigid island
#

what you wrote is nonsense, you don't put methods inside field initializer

steady bobcat
#

I guess we could if we had const functions

restive canopy
#

... alright

#

and right now the var variable can be called upon from the outside script?

rigid island
#

var was meant to be a local variable

#

var is just a stand in for the type returned

#

it puts whatever type your functions returns

steady bobcat
#
public class MyShitMono : MonoBehaviour
{
  private GameObject myObject;

  void Start()
  {
    myObject = Instantiate(myPrefab);
  }
}
rigid island
#

You can do this ^ if you want it to be accesible class wde

restive canopy
#

then why push for var?!

steady bobcat
#

declare field THEN use it later...

rigid island
#

if its local or class wide, thats up to you..

rigid island
#

don't fixate on the var part, it was just used as an example instead of specifying a type
(they are only used in LOCAL variables never in the field declaration)

#

the important part you need to focus on is how to pass a newly object created to another class

restive canopy
#

... and Im back to nowhere

rigid island
#

not really, you have pretty much an outline of what to do

#

you are lacking the very basics of c# so it makes it seems harder than it is

restive canopy
#

alright

rigid island
#

InstantiacingObject = Instantiate(CPU.PlayerPawns.PlayerHall);

then do something with InstantiacingObject

restive canopy
#

because the script that is instantiating all this is persistent

#

I thought the seperate script just "finding" it would be a straightforward process

rigid island
#

It would Find it if by the time it returns the object is in the scene

restive canopy
rigid island
#

but Find is shite mtethod

restive canopy
#

this is still a kick in the gnads

rigid island
# restive canopy

kind useless to show underlin without showing what the actual error is

#

either way this can still run into the same problem with no finding mainProcess by the time Awake runs

restive canopy
#

because mainProcess is hasnt been found yet, Im using variable within mainProcess that dont exist yet

rigid island
#

no

#

its beause you're trying to access properties of MasterInterface inside GameObject type

restive canopy
#

well then if I did just go for the script itself

rigid island
#

there is never a reason to use GameObject type , ever

restive canopy
#

... its getcomponent, isnt it

rigid island
# restive canopy

okay so if it returns you a GameObject, and what you're looking for on the GameObject is a component, what do you think you should write there?

#

god unity why did you fucking change this 3 times

restive canopy
#

this works SO MUCH BETTER

#

oht he headache is gone

#

oh i can think

dense estuary
#

I am very stuck on this.

warm island
#

whats going on with my output?? none of these correlate to my scripts.

languid hound
#

I get these like 1 in every 15 times I navigate the editor in unity 6

#

(Not the same error but a similar error)

warm island
#

yeah this has been going on for awhile and i've just been ignoring it but like its getting annoying pfft

#

is there any like good way to fix it??

languid hound
#

Yeah I wish it didn't happen

languid hound
warm island
#

thats fine but thank you

hexed pecan
warm island
#

maybe

#

im just hoping it doesnt come back but it looks good for now

rigid island
#

unity shits itself sometimes with layouts :p

#

third party tabs or maybe too many tabs arraigned weird , stuff like that

worldly hull
#

texture generation/optimization

#

its complicated, too long, so i threaded it

#

related to texture, but its 100% a coding problem

trail gate
#

um, would anybody mind helping me with my game's inventory system?

vagrant blade
#

You have to ask specific questions to get help

trail gate
#

that's valid. let me arrange my thoughts then

#

I have an item in my game, and an inventory that stores the item as a list, with it's own class to hold the information about the items.
and an equipment script that has it's own spot for an item of the same class. and a playerstats script that updates the stats when an item is equipped or unequipped. that all work ok I think, I'm really new to using lists and classes like this. My problem is that now I want to add the ability to 'absorb' the equipped item, essentially removing the item from the inventory / equipped slot, but keeping the stats attached to it.
I just really can't find a way to remove the item from the inventory properly.

vagrant blade
#

If your inventory is a list of items (ie, List<Item> Inventory), then there is a remove function that comes with using a list collection.

trail gate
#

ahh thank you!

#

I have this line in my equipment script
public CrystalInventory.Crystal currentEquippedCrystal = null;
this creates a new currently equipped item yes? and then I have it update whenever the player selects a different option in the menu.
is that the right way to do equipment? I'm sorry if my questions seem dumb.
but this means that even if I remove the inventory item from the list, the equipped item will still be there, I could just set it to null?

#

I should probably have tried following some tutorials before just writing random code that I think might work.

rigid island
#

it never touches whatever was there

#

if you want to destroy you have to do it while its in the variable
eg
Destroy(currentEquippedCrystal.gameObject)
currentEquippedCrystal = null

#

just like
myList.Remove(myThing) removes only the entry
if you want to destroy it and do stuff with it , you have to use that reference while you have it linked
eg
Destroy(myList[index].gameObject);
myList[index] = null; // making the slot empty again although you can just assign new object here

trail gate
#

hmm I think I understand. I will try it out

flint dagger
#

Can somebody tell me if there's an error in my visual debug or if the visual debug isn't the issue? It is supposed to place spheres on the vertices, which it does correctly, but it's also supposed to draw all the edges which it isn't doing.
https://paste.mod.gg/hhxbrsnusvbb/0

calm wren
#

Does anyone know why a tilemap over a certain size starts glitching with it's colours?

flint dagger
calm wren
flint dagger
narrow sapphire
#

Why would you need that and not an animation event

#

You can just use the animation event to trigger a function to destroy the item once the animation is over

#

Isn’t that exactly what you want

#

Why do you need to specifically use a coroutine

subtle path
#

why is my float 0 ???

mellow sigil
#

Because int / int = int

subtle path
#

but i explicitly create a float variable

#

do i need to cast everything to float before?

mellow sigil
#

Only one of them

subtle path
#

thats weird

#

but thanks, it works now.. i guess?

eager tundra
#

if you want a float division, one of the elements must a be float

subtle path
#

is this really the intended behaviour? it feels so counterintuitive

eager tundra
#

yes, pretty much all the mainstream programming languages work like that

still jungle
lean sail
vestal arch
vestal arch
#

python, and until relatively recently, js, don't, for example

#

they have dynamic typing though, so you usually don't care too much about types

#

(python has a separate operator for explicit integer division, //)

#

anyways yeah most binary operators will give the widest of the operands. int • int -> int, int • long -> long, int • float -> float, double • float -> double

#

int can automatically be converted to long or float or double through "promotion", no info is lost
but float or long to int would potentially lose info; that has to be explicit

crisp flower
#

Im looking into making a savegame system, and will only be saving between level states, so only need to save things like story progress settings, research, skills, resources etc. I'm not sure whether to go with system json, newtonsoft.... I may want to serialize dictionaries and polymorphic might be helpful... unsure on the current state of things

lean sail
#

if you write your save system in a reasonable way, swapping between different json methods should be like a couple of lines difference

crisp flower
#

thanks, I seem to be reading lots of people saying to avoid using newtonsoft if at all possible, to avoid relying on another library, etc etc.

lean sail
#

🤷‍♂️ ive never seen that advice given ever

crisp flower
#

was wondering if the alternate systems are actually fully fucntional these days and if netwonsoft is legacy

lean sail
#

unity's json is JsonUtility, which has less functionality

#

STJ cant be used by default, and people have written downsides before i just cant remember them. So the alternative is writing your own, which of course isn't smart to do

soft shard
still jungle
crisp flower
#

"Don't take a dependency on Newtonsoft.Json if you don't desperately need it. You might end up in a versionning nightmare."
"If there is a possibility to avoid a 3rd party package, I'll take it any time, using STJ is a no-brainer."
"Why would you use an external package if the framework already provides it.
System.Text.Json. Nobody should choose to do it now, but there is a lot of legacy code that uses Newtonsoft because it was the best choice at the time."
"Newtonsoft only exists for backwards comparability and/or legacy systems these days, afaik."
"Do NOT take a dependency if you don't absolutely need it. The cost of eliminating it later usually is high and there is a cost of maintenance."

Some things i read, not my opinions

soft shard
# crisp flower "Don't take a dependency on Newtonsoft.Json if you don't desperately need it. Yo...

From my personal experience with Newtonsoft in both Unity and non-Unity projects, I have never once had a versioning or maintenance issue with it, the most difficulty ive faced is occasionally forgetting the [Ignore] attribute for some types I dont want saved to file, honestly Unitys API would likely change more often than Newtonsoft does, though I can understand in general, wanting to reduce maintaining other packages, plugins, etc on long-term projects

lean sail
crisp flower
#

though that one is not unity specific i guess

lean sail
#

yes thats gonna be the major difference

#

that makes a lot more sense then

soft shard
#

Unity also uses its own package system instead of Nuget, so theres already a lot of 3rd party plugins you cant easily bring into Unity, unless its done through their "Unity Package Manager" (UPM)

quick token
#

surely both of them work just as well as eachother right?

crisp flower
#

cool, I'll use newtonsoft, thanks 🙂

chilly surge
#

The main argument of "STJ > NSJ because it's built-in" doesn't really apply to Unity, it's actually the opposite that it's easier to setup NSJ than STJ.

#

I use STJ in my Unity project because I have more confidence in Microsoft maintaining STJ than NSJ being abandoned with some questionable decisions on top that cannot be removed because of backcompat. But really, either is fine.

soft shard
crisp flower
chilly surge
chilly surge
crisp flower
#

yeah, it's a good point and was also considering.... THanks

devout pivot
#

I'm using this parallax script:

using UnityEngine;

public class Parallax : MonoBehaviour
{
private float length, startpos;
public GameObject cam;
public float parallaxEffect;

void Start()
{
    startpos = transform.position.x;
    length = GetComponent<SpriteRenderer>().bounds.size.x;
}

void FixedUpdate()
{
    float temp = (cam.transform.position.x * (1 - parallaxEffect));
    float dist = (cam.transform.position.x * parallaxEffect);

    transform.position = new Vector3(startpos + dist, transform.position.y, transform.position.z);

    if (temp > startpos + length) 
        startpos += length;
    else if (temp < startpos - length) 
        startpos -= length;
}

}

And when I start the game it makes all 3 backgrounds snap into the same position, what are the possible fixes? the images are the before and after I start the game

quick token
#

!code

tawny elkBOT
soft shard
#

Also, try to keep your question to 1 channel, its less confusing providing help that way

devout pivot
quick token
stable geyser
#

Hey all, looking to create a script that duplicates an existing rule tile and swaps out the sprites in it for sprites in another sheet. I believe I could use CreateInstance to duplicate the rule tile right? But how would I save it as a new file in the editor?

thick terrace
real spire
#

I need a bit of insight, but what would cause the following statement to create a Null Ref Error:

if (EventSystem.current.currentSelectedGameObject.TryGetComponent<Button>(out Button _button){... }

Would this not just return as false if the currently selected object is not found?

It causes an error when I click off my buttons in my test UI, so I assume that EventSystem.current.currentSelectedGameObject would become a null, but I have also tested

if (EventSystem.current.currentSelectedGameObject == null) { ... }

but that also returns as null.

Would anyone have a clues as to what could cause the Null ref error?

vestal arch
#

Would this not just return as false if the currently selected object is not found?
that's what the TryGetComponent would do; but that's not the only thing in that line

#

but that also returns as null.
what do you mean by this?

lean sail
real spire
#

I found the solution.

    EventSystem.current.currentSelectedGameObject.TryGetComponent<Button>(out Button _button)) {
    // Your code here
}```

``EventSystem.current.currentSelectedGameObject is null``, and then when I am trying to call a method ``(TryGetComponent) ``on null, which causes the null reference exception.

I had to first check if ``EventSystem.current.currentSelectedGameObject`` is NOT null before attempting to use it
lean sail
#

It's much easier to follow and that one line isnt so long anymore

real spire
#

Im fine with Null ref errors. I was more worried that it was something to do with the selection system that is within the UnityEngine's event system.

neon frost
#

i am using CineMaschine for a little 3d World of mine. I have a Boss which i would like to put on "look at". But if the Camera is between the player and the boss the player isnt visible anymore. So i thought i could tell the camera to be the furthest away from the Boss as possible. But i dont really know if its possible and how to start

#

or if there is an better alternative

leaden ice
leaden ice
#

Look it up

#

Cinemachine target group

thin aurora
#

When one of the two parts become a float, the operation favours floating type for the result

#

I agree it's weird considering we have methods to determine what to do with the remainder, but I also think it's more consistent.

random raft
#

i need help figuring out how i can go about creating a system where
when you click on the side of two objects where they meet it will join them together and will create a small ball where you clicked and when you remove said ball it will disconnect them and while they are connected you can add more connection balls by clicking on different points along the points where they meet and then you can connect that back to other objects that you have done this to to kind of weld them together and i cant figure out for the life of me how to do it because my first thought was to use parenting but if you tried to attach two points on two seperate objects together the root of the 2nd object might not be the part wanting to be attached to the 1st object and would cause the parenting to get weird and messed up

wintry crescent
#

This might be very silly, but can I convert a Dictionary to a ReadOnlyDictionary without creating a new one?

#

I want a dictionary that is assignable from within a class, but readonly from outside of it

latent latch
#

Iterate over the dictionary and make a ReadOnly out of that

wintry crescent
#

and it'd be a waste to create a new object every time it's accessed

wintry crescent
#

that's wasteful

#

a lot of allocations

#
public ReadOnlyDictionary<IConfigurationManager.GameMechanic, bool> EnabledGameMechanics => (ReadOnlyDictionary<IConfigurationManager.GameMechanic, bool>)(IDictionary<IConfigurationManager.GameMechanic, bool>)enabledGameMechanics;
``` what do we think about this monstrosity?
#

I'd really want to avoid a new allocation every time the dictionary is changed

#

so a conversion would be ideal for me

latent latch
#

Maybe make some dictionary wrapper that has both the dictionary and readonly variation

wintry crescent
#

but this looks just terrible

thick terrace
#

you could just make the type of the property IReadOnlyDictionary maybe?

wintry crescent
#

a wait I missed the I

vestal arch
#

(unless there's a better way idk)

thick terrace
#

yeah, Dictionary implements IReadOnlyDictionary so you can store a dictionary but only allow readonly access by the property

wintry crescent
vestal arch
#

yeah that sounds better

vestal arch
heady iris
#

You can present the dictionary publicly as an IReadOnlyDictionary

vestal arch
#

im not talking about properties

heady iris
#

and then internally store it as an IDictionary (or just a Dictionary)

wintry crescent
vestal arch
#

i don't mean properties

heady iris
#
public IReadOnlyDictionary<int, string> Data => data;
private Dictionary<int, string> data;
wintry crescent
heady iris
#

note that ReadOnlyDictionary is a weird thing from System.Collections.ObjectModel

latent latch
#

Oh yeah that looks neat

heady iris
#

it is a class

latent latch
#

I assume modifying the dictionary works fine too

heady iris
#

you want IReadOnlyDictionary

vestal arch
#
class CanWrite {
  public class PrivateWriteDict : IReadOnlyDictionary {
    private void Set(K, V) {}
    public V Get(K) {}
  }
}
```i mean something like this
(but yeah what fen/simon mention seems easier)
heady iris
#

No cast is needed, since a type can implicitly convert to any interface type that it implements

#

Of course, someone could downcast that back to a dictionary

#

but someone could also just do evil reflection bullshit too

#

this is about signalling intent, not enforcing some kind of security boundary

latent latch
#

Reminds me to actually start making a lot of my data structs to IReadOnly for my scriptable objects

thick terrace
#

the other caveat is that if you get a reference to it as IReadOnlyDictionary the values in there can still change, it sounds obvious but you still have to watch out for stuff like concurrent modification errors

thick terrace
latent latch
#

oh noicee

heady iris
#

ref struct detected

thick terrace
heady iris
#

no heap for you

soft shard
# random raft i need help figuring out how i can go about creating a system where when you c...

If I understand your issue correctly, and these objects have colliders, you could try using the closest point on the objects bounds: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider.ClosestPointOnBounds.html or access the bounds directly to do the math yourself: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider-bounds.html, otherwise if they dont have colliders, you could also get the bounds through the mesh renderer, however the bounds would only give you a cube-like shape that encapsulates the whole space of the object, so if its a rounded object or irregularly shaped object it may not account for that kind of accuracy - if you need that, you could maybe calculate it using a mesh collider or the meshes verts and surface normal from the mesh filter (which may be a more resource-intense approach if your meshes have many verts)

round violet
#

as far as i quickly saw, arrays are more suited if you have a fixed size, and lists for dynamic resizing. is this correct ?

whats the overhead of using a List over an Array ? since the List uses an array internally

rigid island
#

the overhead happens when it just needs to create a new array if the size spilled over

round violet
#

so this means reallocating memory

minor nexus
#

Yes

rigid island
#

it creates array twice the size iirc

minor nexus
#

You can also set an initial capacity if you know your maximum number of elements

#

That way you pay the allocation cost upfront but not the capacity increases (depending on what you need to optimize for)

round violet
#

okay thanks

round violet
velvet nest
#

VS Code just auto-completed this after I had merely typed OnDrawGizmos() lmao

rigid island
velvet nest
#

I have no idea, I just thought it was a funny outcome

#

My guess is some AI-powered intellisense/autocompletion thing during a weird moment.

rigid island
#

weird.. mine works fine

#

IEnumerator Update is hilarious

velvet nest
#

It do be having its own innovative ideas from time to time haha

remote kraken
#

What would an inventory system be classified as? Intermediate or advanced? Cause god damn, I'm ready to smack my head off my desk dealing with this lol

rigid island
#

not all inventories are the same , therefore this is a open ended qustion

remote kraken
#

Well, lets make it more specific, something to the level of stardew valley

#

Pickup, split, drag drop, use etc

rigid island
#

yes thats more intermediate imo

#

complex to me is something like Path of Exile and such

#

mmorpgs / arpgs usually have the complex inventories

remote kraken
#

I can't for the life of me figure out how to get my inventory to not put items in the slot right next to the original stack when that stacks full, pushing other items down slots

#

It's annoying, and I'm getting angry lol

rigid island
#

i think you're starting too complex too early

#

start with a simpler inventory of the same type youre going for but then you can put all the small pieces together

remote kraken
#

I think the problem is not necessarily the complexity, but that how I'm trying to do it doesn't seem to work. Logical thinking lead me to believe "Select slot, check slot has item, if item, add item, if full stack, make new stack, repeat"

#

But that doesn't seem to eb how its working lol

#

I could make a whole inventory system in LUA in like 45 mins, but C# is just kicking me in the balls

#

I've gotten everything setup as far as pickup, and storing the information in lists, updating the UI, just can't seem to sort out how to stop it from adding new stacks of similar items next to one another.

rigid island
#

normally my slot item has a property IsStackable and StackLimit

remote kraken
#

Oh, I'm doing that differently, my maxStackSize is implemented in the items itemData itself.

rigid island
# remote kraken

thats fine
as long as you can access it, doesnt matter where it is usually

remote kraken
#

But the bulk of my issue is in the following

wheat spruce
#

whoever posted the picture of that game object with a scale of 100,100,100, you really should alter the scale factor of the mesh

#

setting an object to such a large scale, because the model happens to be very tiny when imported, is never a good idea

#

set its scale to 100 in the import settings

rigid island
wheat spruce
#

well, hopefully not notlikethis

remote kraken
rigid island
#

but thats probably discord ig

wheat spruce
rigid island
#

I put it in my IDE and it autoformatted

remote kraken
#

Yeah looks fine in my IDE

rigid island
tawny elkBOT
remote kraken
#

bleh, okay

rigid island
#

hard to read big code on discord

wheat spruce
remote kraken
#

No clue, discord does dumb things

#

I think the only other relative code ineeded for that is this

    {
        if (icon == null || countText == null || itemNameText == null)
        {
            Debug.LogError("InventorySlot UI elements are not assigned!", this);
            return;
        }

        // Update the slot UI
        icon.sprite = itemData.icon;
        countText.text = stackSize > 1 ? stackSize.ToString() : "";
        itemNameText.text = itemData.displayName;
        gameObject.SetActive(true); // Ensure slot is visible

        // Re-enable UI elements to refresh
        icon.enabled = false;
        icon.enabled = true;
        countText.enabled = false;
        countText.enabled = true;
        itemNameText.enabled = false;
        itemNameText.enabled = true;

        // Set current item data
        CurrentItem = itemData;
        CurrentStackSize = stackSize;

        Debug.Log($"Slot Updated: {itemNameText.text} | Count: {countText.text}");
    }

    public void ClearSlot()
    {
        icon.sprite = null;
        countText.text = "";
        itemNameText.text = "";
        CurrentItem = null;  // Clear the current item reference
        CurrentStackSize = 0; // Reset stack size
        gameObject.SetActive(false); // Hide empty slots
    }```
wheat spruce
#

for what its worth, if you saved the file as text.cs then uploading the file will automatically format it correctly to show the coloured text

remote kraken
#

I ran into an issue where it'd just completely destroy my UI, so I had to hardcode refresh

remote kraken
wheat spruce
remote kraken
#

Interesting. Good information to know for the future

rigid island
#

not really tho

#

files dont work on mobile

#

usually they dont get embed

remote kraken
#

I've never used mobile =p

wheat spruce
#

funny how much mobile differs to the desktop

rigid island
remote kraken
#

I dont wanna listen to the 70+ discord servers pinging me on my phone lol

wheat spruce
#

they only recently added a way for mobile to play uploaded audio files

rigid island
#

the whole point of using those link sites

#

so people can better read your code

#

so they can better assits, if its a hasstle, no one is gonna bother

remote kraken
#

fair enough point

#

I'm small minded for thinking most people use desktop versions of discord over mobile

#

But I've also been using discord since before mobile was really prevalent.

#

God, I've been on discord for almost 10 years now lol

still jungle
#

well people do other activities than sitting at PC for whole day, but the phone is still in the pocket

remote kraken
#

I'm the opposite, my phones typically not with me.

still jungle
#

so still can reach for it and help

remote kraken
#

I'd rather throw my phone on charger or a shelf and go do my business, if I'm at my computer, my phone sits on my desk

#

Probably one of the smaller margin of millennials that don't have themselves glued to phones in some sense

#

But I also have 4 kids, so I don't really get the luxary of using my phone

slate ether
vestal arch
#

multiply boxOffset by transform.forward

#

for future reference, !code

tawny elkBOT
slate ether
#

thank you

round violet
#

can i expose to inspector a list of a scriptable object/class, and make each entry already "instanced" ? like if it was a struct

rigid island
heady iris
#

The object isn't contained directly

#

But for plain-old classes or structs, yes

round violet
round violet
heady iris
#

nav showed an example of a field with an initializer that gives it two items by default

#

any new instance of the component you put that in will have those two objects stored in the list

#

that does mean that you're going to create that list every time the class is created (including when unity creates it and then immediately replaces its contents)

#

Maybe you're looking for the Reset method? That lets you run code when a component is added or reset via the inspector

round violet
#

are you familair with unreal ?

#

im looking for something similar to the Instanced prop meta, or InstancedStructs

#

basically the editor instances a object of the type you choose, and will show you all the exposed props
it will serialize with the container

rigid island
#

im kinda confused what ur asking now lol

round violet
#

a bit like nav example, but with just new MyClass()

rigid island
#

then just give the default values in the field initializer of MyClass

somber nacelle
#

provided the type is serializable, that is already how it works

round violet
#

i guess structs are what i have in this case

rigid island
#

a friendly way would probably be creating some fields in the inspector to then pass to the constructor

round violet
#

that wouldnt work fine if i wanted a list of unkown size

rigid island
#

why not?

somber nacelle
#

what have you actually tried and what exactly isn't working with what you've tried? because everything you've described that you want so far is pretty much how it already works

rigid island
#

the editor window can be the one that setups the values for the new() List

round violet
# rigid island why not?

because this means i have to manual write all props needed to init a new instances X the count i need ?

rigid island
#

Idk what the usecase is exactly so not sure what to suggest.. but there are ways to mitigate that with default values no?

#

whats "manual write all props " mean here

round violet
#

idk what i previously tried but now it works

#

sorry for the inconvenience

#

i guess scriptable objects are a bit special for the serialization system

somber nacelle
#

like Fen already pointed out, UnityEngine.Object derived objects are all serialized as a reference to the object rather than serialized in place like plain classes/structs. this is why when you create a serialized field of some UnityEngine.Object type you'll see a slot to drag one in

buoyant geyser
#

hey if i need help with smth is this the right channel to go to

#

having a really stupid problem where a knockback force works when positive but not when negative

#

and chatgpt is running in circles

vestal arch
#

well if a knockback force is negative wouldn't it go in the opposite direction

buoyant geyser
#

thats what im saying

rigid island
#

unless you are overriding it with velocity

buoyant geyser
#

for context im tryna make a little platform fighter for ffun and player one is always on the left and player two is always on the right. their code is basically identical besides variable names and stuff but obviously to knockback player 1 it needs to be negative

buoyant geyser
#

its not a hitbox prooblem either i brought the player forward on the z axis so there shouldnt be any collision

vestal arch
buoyant geyser
#

they cant jump over each other im making this very simple

vestal arch
#

ok, so apply a positive force in the direction you want

#

nothing needs to be negative there

buoyant geyser
#

thats what i did:
new Vector2(direction * force, rb.velocity.y)

#

and direction is either -1 or 1 depending on what player you are

vestal arch
#

ok, how are you using that vector

buoyant geyser
#

ill cvopy paste it rq one sec

vestal arch
#

see !code

tawny elkBOT
buoyant geyser
#

nah its one line

vestal arch
#

ok use single backticks instead to get inline code formatting

buoyant geyser
#

float direction = isPlayerOne ? -1f : 1f;
playerRb.AddForce(new Vector2(direction * force, 0), ForceMode2D.Impulse);

mb two lines

#

i dont think the backticks woorked lol

vestal arch
#

backticks before and after

buoyant geyser
#

oops sorry

vestal arch
#

you could make this more readable by using Vector2.left or Vector2.right instead

buoyant geyser
#

i mean i guess but would that change anything

vestal arch
#

not really, but it'd make mistakes less likely

#

what's the issue though?

#

kinda missed that

buoyant geyser
#

basically whenever the direction is positive it works but when its negative it just doesnt its very strange

#

like ive tested positive forces on both players and negative on both, positive always works and negative never dooes

vestal arch
#

what do you mean by "it doesn't work"

#

that's very little info to go off

buoyant geyser
#

youre so right sorry

#

theres like 0 movement at all

#

no matter how much i juice up the force by like theres NO knockback whatsoever

#

ive been at this for hours i have never seen a more stupid issue

leaden ice
#

Share the full script

buoyant geyser
#

but it works when the numbers positive with no interference

leaden ice
#

I could easily write code that behaves that was

buoyant geyser
#

the scripts like 550 lines long should i just send the method

leaden ice
#

That's really short

#

!code

tawny elkBOT
buoyant geyser
#

oh fr

leaden ice
#

Use a paste site ^

buoyant geyser
#

ok i use two scripts for this ones the general combat script and ones the movement so ill just send both

#

keep in mind i realized a way more efficient way to do it when i was already almost through so it might be a bit inefficient

rigid island
buoyant geyser
#

the knockback part i showed is at the bottom of the player combat script

buoyant geyser
rigid island
buoyant geyser
rigid island
#

all good

leaden ice
#

so any forces you add will essentially be overwritten entirely by this

buoyant geyser
#

not when the force is positive though

#

when direction is positive it works

rigid island
buoyant geyser
#

so nothings being overwritten

rigid island
#

it is tho

buoyant geyser
rigid island
#

check the bool

#

make sure it is what you expect

leaden ice
#

this structure with p1IsKnockedBack and p2IsKnockedBack is weird. Why do that with two separate variables instead of just making that a field on the player movement script itself

buoyant geyser
leaden ice
#

the fact you've presumably got two separate scripts that do the same thing for the two different players is also kinda 😵‍💫

buoyant geyser
#

bro yeah ngl i made this project a long time ago but gave up on it and revisited it and it was already structured like that so i kinda js kept it

velvet galleon
#

why toeballs

buoyant geyser
#

but yeah horrible way to do it

#

hey hey lets stop judging my horrible style and get to the bottom of the issue

leaden ice
#

by the way are you modifying knockbackForce in the inspector? or just in the script?

buoyant geyser
#

i was playing around with it in the editor to ffind a number i liked

#

like the most confusing part is that the code is fully functional when direction = 1 but dooesnt work when direction = -1 thats why im saying like it cnat be an overwriting issue

leaden ice
#

yes but in the inspector or in the code?

buoyant geyser
#

inspector

leaden ice
#

ok good

buoyant geyser
#

140 kinda high i dont remmebr if thats what it says in the code but im pretty sure lol

leaden ice
#

The wother weird thing I'm seeing is...
in the LandsHit method you do AddForce
then it does StartCoroutine(StunPlayer(false, stunDuration));
And inside there you do:
StartCoroutine(ApplyKnockback(player1, knockbackForce, 0.25f, true));
which again does the AddForce

#

Why are we adding force twice

#

And maybe you mixed up your directions in that chain somewhere

#

which could mean that one of the force directions is getting canceled out when you add the second force

buoyant geyser
#

i dont understand wheres the second time

velvet galleon
leaden ice
#

YOu're adding force on line 338 and line 360

#

in your link

#

and both of those are to the right no matter what

#

so if you then add a left force in the other place, it cancels out to 0

#

if you add a right force it doubles

#

you probably want to just delete the AddForce on line 338 and 360

#

inside p2ExecuteAttack and p1ExecuteAttack

buoyant geyser
#

YOOOOOOOOO WAIAT

#

i love you guys

#

thank you so much

#

silly ahh mistake but much appreicated everyone!!!!!

sacred python
#

hi guys im new to unity and unity networking with netcode
im trying to displat info about an annotation object (prefab) when is hovered
is working for host, but not for client ( is just an empty string)

void Start()
    {
        if (!IsOwner) return;

        _camera = GameObject.FindGameObjectWithTag("PlayerCamera").GetComponent<Camera>();
    }

    void Update()
    {
        if (!IsOwner || _camera == null) return; /

        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);

        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, _layerMask))
        {
            AnnotationComponent annotationComponent = hit.collider.GetComponent<AnnotationComponent>();

            if (annotationComponent != null)
            {
                RequestAnnotationInfoServerRpc(annotationComponent.NetworkObject);
            }
            else
            {
                HideAnnotationClientRpc();
            }
        }
        else
        {
            HideAnnotationClientRpc();
        }
    }
#
[ServerRpc]
    private void RequestAnnotationInfoServerRpc(NetworkObjectReference annotationObject)
    {
        if (annotationObject.TryGet(out NetworkObject annotationNetworkObject))
        {
            AnnotationComponent annotationComponent = annotationNetworkObject.GetComponent<AnnotationComponent>();

            if (annotationComponent != null)
            {
                string info = annotationComponent.Data.Value.info;
                Debug.Log($"Sending annotation info: {info}");

                // Send the annotation data to the client
                DisplayInfoClientRpc(info, true);
            }
        }
    }
    
    [ClientRpc]
    private void DisplayInfoClientRpc(string info, bool showInfo)
    {
        if (showInfo && !string.IsNullOrEmpty(info))
        {
            Debug.Log($"Received annotation info: {info}");
            _annotationInfo.text = info;
            _annotationCanvasInfo.SetActive(true);
        }
        else
        {
            _annotationCanvasInfo.SetActive(false);
        }
    }
    
    [ClientRpc]
    private void HideAnnotationClientRpc()
    {
        _annotationCanvasInfo.SetActive(false);
    }
#

i dont know whats wong
any advice is welcome

sacred python
#

oh thank

low ravine
#

how does the unity library ecosystem work?
What would I need to do for my library to make it so that unity developers can use it?
so far i support dotnet6/7/8 and publish to nuget but i see conflicting information online about whether or not that is enough

wheat spruce
rigid island
wheat spruce
#

the way the netcode is written has a general LLM feel

low ravine
rigid island
wheat spruce
#

I dont envy the task debugging gpt netcode 😅

rigid island
low ravine
#

for some more context im working on an ecs/ec

#

and want it to be able to be used in unity

rigid island
low ravine
#

dotnet 4 😭
wild

rigid island
#

yeah sadly

wheat spruce
rigid island
#

hopefully unity 7 brings in the new "Core" CLR

rigid island
low ravine
#

by .NET 4 you mean any dotnet framework 4.x right?

rigid island
#

correct

low ravine
#

ok at least its something in support xD

rigid island
#

Its mainly the speed , most other things are syntactic sugar

#

.net 4 is painfully slow compared to .net 9

low ravine
#

oh god

#

wait.. no spans?

rigid island
#

iirc some stuff is omitted but you can put the dlls back

#

unity just picks and choose specific dlls

#

had to do the same for other things that normally are available in 4

low ravine
#

mm
i see

rigid island
#

sometimes you also have to switch it from standard 2.0 to 4.x for dll to work

low ravine
#

polyfill time

leaden ice
flint dagger
#

Really? Compute shaders aren't really just shaders... They're some bizarre middle ground. But if you say so.

leaden ice
#

they are shaders - it's right there in the name!

#

and when you consider that the programming paradigms and languages involved are exactly the same as regular shaders, it makes a lot of sense to ask those people.

wheat spruce
crimson plaza
#

If i subscribe functions using a lambda expression how do I get them to unsubscribe if I don't even have the function identifier?

#

Or should I just not use lambda expressions in this case then

leaden ice
#

It's really usually best just not to use a lambda here instead

west lotus
#

Just dont use lambdas to subscribe to events. To me at least thats code smell.

#

Unless it is a one shot type of event that can do it’s own cleanup like a OnComplete

wheat cargo
#

Producer objects will keep their subscribers from being garbage collected but the same is not true for the reverse case.

#

This is why static events are extra dangerous, not unsubscribing from them can lead to memory leaks and undesired behavior.

crimson plaza
#

Why must my derived class have a constructor with parameters if the base class does not have a parameterless constructor?

#

the problem is solved by implementing a constructor that has parameters which is very weird to me

wheat cargo
#

You can get around this by setting the constructor in the base class to a private parameterless constructor and using static factory creation methods instead

wheat cargo
crimson plaza
#

What if my derived class doesn't need to override the base constructor and just have it call the base constructor anyways?

#

Does this mean that the "contract" is now the parameter'ed constructor like here?

thick terrace
wise kindle
#

Does anybody know where I can find the radius float with a cinemachine camera? I've been trying to search within the class but I cannot find anything within its structs. Also, if anyone knows a way to find a specific variable within a script and all its structs/classes i'd be so thankful

#

Nevermind, it's not in the cinemachine camera class, it's in the cinemachine orbital follow

quick token
swift falcon
thin aurora
#

Events take a method reference

#

You subscribe with one, you unsubscribe with one

#

Anonymous lambdas don't have a reference stored so if you use the same one in the unsubscribe call it will be a new reference, not the same one. That doesn't work.

swift falcon
thin aurora
#

As a general remark not aimed at anybody in specific

#

Same thing as when you compare classes, the default behaviour is by reference. Methods work the exact same way. Delegates are essentially variables like classes would be.

golden vessel
#

Hello, I want to make a system with seeds to handle anything that's random in my game, but I have no idea how to go about it. Any insight/resources?

leaden ice
#

Youi could use Unity.Random or System.Random as two simple examples

#

initialize it with your seed

#

then generate the random stuff as normal

golden vessel
#

That's really useful i didn't know that was a thing thanks a lot

wintry crescent
#

Can I "chain" a coroutine so that it can be invoked at any time, but it will run the moment the gameobject is enabled?

wintry crescent
leaden ice
#

start it in both

#

not sure i understand the question

wintry crescent
leaden ice
#

what does chained mean

swift falcon
#

I have a general question about a function that I can't figure out how it works, and the documentation and stuff online doesn't make much sense. Would I ask here?

wintry crescent
swift falcon
wintry crescent
#

I suppose

swift falcon
#

it makes zero sense.

wintry crescent
quick token
swift falcon
# wintry crescent how does it make zero sense?

I need to add an onclick event to a button when instantiated. It might be that I can use this, but I have no idea. There is not much documentation at all about onclick events, it seems that they are mostly just part of the inspector view and not the actual thing happening

quick token
quick token
wintry crescent
swift falcon
wintry crescent
#

!code

tawny elkBOT
swift falcon
#
    public void CopyTask(string newTaskData)
    {
        //do not fix or TOUCH AT ALL if this is touched everything breaks!!!
        //do not optomise in fear of project collapse
        Debug.Log(transformYValue);
        transformYValue = transformCount * -150; //makes distance farther for every new task
        GameObject newButton = Instantiate(buttonPrefab, new Vector3(0,0,0), Quaternion.identity, buttonParent.transform);//creates new button

        newButton.gameObject.GetComponent<buttonStringKeeper>().buttonString = newTaskData;
        transformCount ++; //increases distance for next
    }
#

not my first time

wintry crescent
swift falcon
#

the second one that the button needs to call is:

    public void OpenOverlay1FromInspector()
    {
        GameObject clickedTask = GameObject.FindWithTag("TaskClicked");
        string messageAndPoints = clickedTask.gameObject.GetComponent<buttonStringKeeper>().buttonString;
        //^^^finds task that was clicked and takes it's string
        string[] splitData = messageAndPoints.Split('|');
        string message = splitData[0];
        int points = int.Parse(splitData[1]);
        string link = splitData[2]; //should set 3rd split value to link
        OpenOverlay1(message, points, link);
        clickedTask.gameObject.tag = "Untagged";//untagges tag
    }

the current way is adding a tag when it's clicked and then using that to find the script component with the variable and then removing the tag

quick token
swift falcon
#

not really. I'm not well versed in this

quick token
swift falcon
#

sorry I'll have to ask later I gotta run, in between classes now.

wintry crescent
#

although do watch the video that not jordan sent

#

understanding why this is the solution, will be helpful

quick token
quick token
lean sail
wintry crescent
quick token
quick token
lean sail
#

you really dont need to use EventHandler in unity

quick token
lean sail
#

what, no. you just simply dont need EventHandler. its not "simplified" by UnityEvent

#

CodeMonkey's tutorials have generally been known to not be so good. If you wanna learn c# events just follow a basic tutorial that isnt unity specific

quick token
lean sail
#

my comment was specific to the point of "in unity though its simplified by UnityEvents"

quick token
#

i dont really see what exactly you're confused by there. i honestly haven't looked into the UnityEvents docs that thoroughly but from experience thats just how they've worked

lean sail
quick token
#

code monkeys tutorials have been fine to learn from for me. bit complicated and long but they're not that bad.

lean sail
heady iris
#

jordan is talking about C# events vs. UnityEvent

lean sail
#

yes and i am saying their claim is wrong that "in unity though its simplified by UnityEvents"
Nothing here is simplified by UnityEvent. You don't use UnityEvent as a replacement for EventHandler, 1 because you dont need EventHandler at all to use c# events in unity. and 2 because the purpose of UnityEvent is to make it show in inspector

quick token
lean sail
#

considering we're in a unity context, why does he use it throughout the entire video?

quick token
#

which y'know, is the title of the video.

heady iris
#

i think EventHandler (the Unity UI component) has gotten mixed up with C# events

lean sail
# quick token its basic c#

if you're trying to claim his video isnt specific to unity, please scroll through any of the video and look at the actual code

quick token
heady iris
#

I don't understand what your point is

quick token
#

i think they just dont like code monkey, which is fair enough i guess. there's other tutorials out there.

lean sail
#

its not about if I like them or not. ive written it twice above, the quality of their tutorials is just not that good

naive swallow
#

So, I have a lot of line renderers. Displaying a bunch of data all at once, and I need to know when a specific line is clicked on. Way too many for even a Capsule Collider to run decently well on. I have the lines generate their capsule on start, and they never move, but they're still nuking my framerate when they're on screen.

Is there a way I can either:

  • Make a capsule collider significantly more lightweight
  • Detect when I click on a line renderer using pure math at time of click rather than keeping a collider around
quick token
cold parrot
naive swallow
#

Ballpark, I'm guessing about a thousand, but I can get an accurate count in a bit

vagrant blade
#

Job system time

cold parrot
#

i would expect you can have a couple thousand if you don't have them all bunched up, which would mess up your broadphase

naive swallow
cold parrot
#

i have a scene with ~10k static box colliders all inter-colliding, but none of their AABB overlapping, that causes no performance issues at all

naive swallow
#

Maybe I should try box colliders instead of capsule? Would that make a huge difference?

cold parrot
# naive swallow They're pretty bunched actually

you could render them to a 16 bit render texture with each line having a different color, then check the pixel on that render texture you are clicking on, assuming you want the topmost one, that would be quite easy to make

lean sail
cold parrot
#

i would expect your issue to be primarily that the BVH of the physics system will have to check too many colliders in its narrow phase

naive swallow
#

If I put them on a layer that could not collide with itself, would that help at all?

leaden ice
#

how are they created/generated?

naive swallow
leaden ice
#

we might be able to build up some kind of queryable data structure from that same data

#

though I guess we'd be hard pressed to make something more performant than PhysX's system?

vagrant blade
#

Is this 2D or 3D?

leaden ice
vagrant blade
#

Or rather, 2D or 3D plane

naive swallow
#

Essentially, I have a bunch of data about where a gunshot could happen and data about how much damage it might do and to what, and I'm trying to draw a line for each one, and let someone click on it to get that additional info

#

Some big fancy math program computes "Someone standing at this location and firing at this angle at some building or vehicle with this caliber has a XX% chance of injuring someone on the other side" and stores it in a file, I'm parsing it and showing those lines for people to get a visual idea of what the numbers mean. If someone wanted to be incredibly thorough, they could simulate essentially a sphere down to individual degree resolution for multiple types of weapons, which would generate a lot of data. I'd like to at least somewhat try to display that data

cold parrot
naive swallow
#

Yeah, that seems the most feasible, I'm just working on implementing it

cold parrot
#

you would probably need some sort of compute shader so you don't have to CPU-query the texture

naive swallow
#

Okay, so, rough approximation:

On mouse click, rasterize images to render texture
Do some sort of magic shader thing to mask out everything but the lines and then give each line a unique color identity
Get screen coordinates of mouse, convert to coordinates of render texture
Query pixel at that location, look up which line has that color identity
Execute "clicked on" functionality of that line

cold parrot
naive swallow
#

I had to do something kind of similar when trying to save a normal map from a runtime-loaded mesh as an asset in the project with an editor script, it'd be something like this, but I'd need a new shader that does this "no graphics, lines only, final destination" thing?

Texture2D dest = new Texture2D(baseMap.width, baseMap.height);
RenderTexture renderTexture = RenderTexture.GetTemporary(baseMap.width, baseMap.height);

if (isNormal)
{
  Material blitMaterial = new Material(Shader.Find("Hidden/DXTnmToRGB"));
  Graphics.Blit(baseMap, renderTexture, blitMaterial);
}
cold parrot
#

Actually you would have to only render the pixel around the pointer, and the shader could be ObjectID in a channel of TextureFormat.RG32

sick hawk
#
try {
    action.Do(this);
} catch(Exception e) {
    e.Message = $"Error occurred in state {stateName}.{eventName}.{i}" + e.Message;        
    throw e;
}

is there any way to do something like this? I would like to be able to see where the error occured so I can more easily figure out what the issue is

#

idk how ur supposed to do this sort of thing in unity

cold parrot
sick hawk
#

the problem is the stack trace doesn't have all the info I need

#

im trying to add it

cold parrot
#

or call a Debug.LogError/LogException in it

sick hawk
#

I tried that but it doesn't include the proper trace for some reason ill try the debug.log thing

cold parrot
lean sail
vestal arch
#

i think it'd generate a new stacktrace? not sure

lean sail
#

try printing out e.StackTrace

sick hawk
#

it just shows the trace of the throw not where it originally comes from

#

I tried inner exception because I remembered that working before but then it just displayed the original without the new stuff

sick hawk
vestal arch
sick hawk
#

Debug.LogError($"Error occurred in state {stateName}.{eventName}.{i}" + e.Message + e.StackTrace); this seems to work ok

lean sail
#

in the case above, what extra stacktrace are you expecting? its not like you're calling fixedupdate yourself

#

i normally avoid trycatch, unless these are errors out of my control. stuff like user input or files

sick hawk
#

i wanted the original stack trace just also with the info about which state and action it occured in

#

which the above works so im happy

lean sail
#

if you didnt have it in a try catch it should just print out all the info normally

sick hawk
#

it didn't have the info I need

#

look its fine I got a workable solution

leaden trench
#

in 2022.3, is there a method to make a navmesh agent face a raycast point without moving to it?

lean sail
#

the way it rotates by default is very weird to me

vestal arch
#

please don't crosspost

scarlet kayak
#

i used the paste mod one

vestal arch
scarlet kayak
vestal arch
#

ah yeah the paste sites don't really give instructions

candid fossil
#

I'm having a problem with knowing how to implement scriptable objects as data containers for gameObject stats.
I get that I can have a ScrOb with Health, color etc, and a gameObject prefab with those same properties. But is there a design convention around how to get that data onto new objects correctly?
Should the prefab have some kind of constructor function that populates its stats from the ScrOb?
Should there be a 3rd script created that is just a maker that instantiates the prefabs?
Should an enemyManager or InventoryManager be filling its own list with a construction script that copies the data onto the prefabs?
I can follow the idea through a tutorial, but I seem to fall apart especially when coding something to handle groups of enemies as the Encounter is a ScrOb that has a list of Enemy ScrObs, but how to spawn that out into the game gets messy.

lean sail
# candid fossil I'm having a problem with knowing how to implement scriptable objects as data co...

usually SO is the abbreviation of scriptable object
i wouldnt say there is really a design because its just a matter of copying the data from the SO to your code. You mention a SO with "health, color, etc" and a prefab with those properties, well the GameObject doesnt know anything about health or color. You must already have some script on those prefabs for these values. In that script, you can have a reference to the SO you want it to copy data from. In awake you can copy the data

candid fossil
#

I feel like I get that part. Like I have an enemy script, and an enemy prefab with that script attached as a component, and an enemy SO where I can design and tune enemy values.
During awake, how does the enemy script get the reference to the enemyA SO that it should populate data from?
When I want to spawn a group of enemy A, vs enemy B, is there any convention as to what should be passing the enemy SO to the enemy script?
Examples I follow feel like they especially break when I get to a SO that has other SOs in it.

lean sail
#

presumably, enemy A would be its own prefab. Enemy B would be its own. You assign whichever SO you want to each prefab

uncut plank
#

I have a top down game, im procedurally tilting the character model based on input. but when i rotate the character model to say look left, and then i start moving, it tilts based on its rotation so clicking W which moves you up it would Yaw left instead of pitching down, how do i make it tilt based on world XYZ or even based on the Character Controller rotation which doesnt rotate?

candid fossil
lean sail
candid fossil
lean sail
#

part of this is also dependant on your game itself, so its a bit easier to help if you have specific examples you need this for

candid fossil
#

Okay, lets use a more expressive example. If I had pokemon prefabs. I could make a bulbasaur prefab, and have SOs for a level 5 and a level 30 version. And I could do the same for a charmander prefab and SOs.
But with most of the same properties, couldn't I just have one pokemon prefab, and then SOs that load name, stats, sprite, moves etc?
Either way, I think I understand the difference between those two implementations, but once you walk into an enemy trainer, they have a list of pokemon. A "team" SO, that is a list of pokemon SOs, each of which has a list of 4 moves, also SOs.
I'm more interested in designing the right flow for what mechanism tells the battle screen how many prefabs to load up, how to pass each prefab the SO it needs, and then which script should be responsible for copying the data from the SO onto a given instance.
If I pass each prefab an SO, and it copies data out of the SO, onto itself that's fine, but I think I'm missing some kind of manager that keeps these prefabs wrangled in a list so you can actually target them. And with multiple layers of SO I keep getting errors where parts of a prefab want a finished Move object, not an SO of a move.

glossy mortar
#

I just used chat gpt to make some very specific code that I didn't bother to make by myself

#

I just needed a script that makes a new render texture and a new material variant for every instance of that object so that they don't interfere with each other

latent latch
#

As for passing stuff around, you can always make some like lookup table where you bind these prefabs/SOs, but it's not always needed depending how you're serializing these prefabs. For instance, you have pokemon grouped by zones, so instead of having to access this global lookup table you just look at the current Zone data and grab it from there.

torpid valve
#

Where can I get help with the problems I experience while developing a game?

somber nacelle
#

!ask

tawny elkBOT
lean sail
# candid fossil Okay, lets use a more expressive example. If I had pokemon prefabs. I could make...

got caught up with work
i dont know if you really wanna use SO like this. you could have one prefab and SO's representing every pokemon but it starts to become really tedious. Yea you'd save a tiny bit of memory but i dont know if this is worth the effort. You'd also have to figure out a way to assign the SO to a prefab. Like when you want to spawn bulbasaur, whichever script is responsible for that needs to look up what the bulbasaur SO is (or have a direct reference to it already).
I think the initial sentence you had was good, a bulbsaur prefab and SO for the stats. The SO could even link to the next evolution (a prefab)

As for the enemy trainer, I think you might be going overboard with the SO's. Maybe. A team SO could just be a list on your monobehaviour on the prefab. Idk if you're ever gonna be reusing teams. A list of pokemon SOs would be avoided if you had a prefab per pokemon (tying into the 1 prefab and many SO discussion). I could see the moves being SOs but again you'll need to find a way to map these. If a pokemon move changes, you'll need to store that in a file. When you read that file, you gotta figure out which SO it corresponds to. Be careful for the moves as an SO too if you ever need to store "state". Like if an attack needs to store information, you shouldn't do this inside an SO because everything referencing this move will be referencing the same instance.

candid fossil
night harness
#

Just another two cents being thrown into the well. a mix of ScriptableObject's and POCO/base classes could be nice here

#

a ScriptablePokemon per pokemon to define stuff like display name, element type, pokemon description, sprites etc. and then a poco class of base stats used to roll the real ones when caught (in this screenshot they are standard sliders but you would want cooler minmax ones to decide the values it could be rolling from)

#

then trainers could be defined as a ScriptableTrainer that uses a TeamPreset like this (the player could use this too)

[System.Serializable]
public class TeamPreset
{
    [field: SerializeField] public PokemonWithPreset First { get; private set; }
    [field: SerializeField] public PokemonWithPreset Second { get; private set; }
    [field: SerializeField] public PokemonWithPreset Third { get; private set; }
    [field: SerializeField] public PokemonWithPreset Forth { get; private set; }
    [field: SerializeField] public PokemonWithPreset Fifth { get; private set; }
    [field: SerializeField] public PokemonWithPreset Sixth { get; private set; }
}


[System.Serializable]
public class PokemonWithPreset
{
    [field: SerializeField] public ScriptablePokemon Pokemon { get; private set; }
    [field: SerializeField] public PokemonValues Values { get; private set; }
}

Where you use a pairing of the templated pokemon values along with the instance of PokemonValues for dynamic modification. (This looks abit ugly in the inspector by default but some pretty basic editor programming could show them more inline, any general editor extension package likely has options to do this for you too)

rugged fulcrum
#

Might be a stupid question but im trying to instantiate a Camera from a prefab in DOTS, ecb.Instantiate(camera_prefab) However I can't set the camera to the main camera, the game view remains blank. Even after setting MainCamera in the prefab descriptor and ensuring it's the only camera in the scene.

unkempt meadow
#

!code

tawny elkBOT
unkempt meadow
#
void Update()
    {

        PlayerRotation = Player.transform.rotation.eulerAngles;
        RotationAdjusted = new Vector3(PlayerRotation.x, PlayerRotation.y + 180, PlayerRotation.z);
        transform.rotation = Quaternion.Euler(RotationAdjusted);

        SurfaceNormals = RotationFSM.FsmVariables.GetFsmVector3("left hand normal").Value;
        Debug.Log(SurfaceNormals);

         Quaternion TargetRotation = Quaternion.FromToRotation(Vector3.up, SurfaceNormals);

         transform.rotation = TargetRotation;

OK so I'm trying to convert some code from playmaker to c#. I thought I did a 1 to 1 conversion but the c# version doesn't seem to work properly.

You might be confused as to why I would set the rotation twice in 1 frame. The reason is I am trying to align a hand to a surface normal but this rotation doesn't take into account the direction the player is facing so my hand would rotate fine in one direction but would be broken by 180 degrees when I turn around.

Setting it like this fixed the problem, somehow.

rugged fulcrum
unkempt meadow
lean sail
unkempt meadow
lean sail
rugged fulcrum
unkempt meadow
#

ok it didn't quite fit but the last action just aligns the Y axis to the surface normals

#

I was trying to replicate the same thing in C#

lean sail
unkempt meadow
#

it just gets a Vector3 variable from a playmaker FSM. So, a script

lean sail
#

well yes i can see that given how its used and the name...

#

the question is what math its actually doing to get these values

unkempt meadow
#

In that fsm, I raycast to get the surface normals and try to align a hand to them. I use the same variable to do this in a playmaker fsm and it works there, doesn't work here and I don't know why

lean sail
#

maybe you want to multiply the current rotation instead?
transform.rotation *= TargetRotation;

unkempt meadow
lean sail
unkempt meadow
#

in playmaker, that didn't work cause I'd align the hand perfectly in one direction but when I turned around in the opposite direction, my hand would be broken by 180 degrees

#

doing that double rotation fixed it

lean sail
#

i think you should stop focusing on what you did in playmaker because i am pointing out glaring issues for you on why exactly your current method doesnt work

unkempt meadow
#

I am just trying to explain why I did double rotation

lean sail
#

and i explained why the double rotation you did doesnt actually do anything..

#

it doesnt matter if you assign it twice, or 100 times, if you are just overwriting it without using previous values in some calculation, it does nothing

#

again its really hard to visualize what your code does because theres so many unknowns there. Idk if this is what you actually need but maybe just try what i said with the last line. multiply the quaternion, which is like adding the rotation
transform.rotation *= TargetRotation;

#

with this, you would actually be using the previous rotation in your calculation. its adding the rotation rather than completely overwriting it with an unrelated value

unkempt meadow
#

I actually did try that but I got a slightly innacurate result. Let me try again but I'll remove that other code that should be reduntant

dusk apex
#

Just in case it was over looked, reminder that a quaternion isn't the same as an Euler and should not be used as the value for the Euler method.

unkempt meadow
#

also it's getting way to late here, I'll deal with it in the morning

lean sail
unkempt meadow
#

I will improve

dusk apex
#

Nevermind.. I may have mislooked

lean sail
#

when it comes to rotation stuff, id add a ton of debug lines to visualize. printing out values doesnt really mean much to me

heady iris
#

(there is no reason to do this)

#

you just use the Quaternion methods to manipulate rotations

wheat cargo
#

Is there a way to store a scriptable object's property immediately to disk without saving the entire project?

somber nacelle
#

are you doing something like changing the value in code? 🤔

somber nacelle
wheat cargo
somber nacelle
#

have you actually tried it? because it works for me

heady iris
#

this explicitly writes an asset to disk

wheat cargo
#

Okay thanks!

heady iris
#

note that it will not mark the asset as dirty

wheat cargo
#

Yeah I'll set dirty then call that

#

ty!

fervent juniper
#

Hey guys, im having some issues with a line renderer projection

private void LineRendererTrajectory(Vector3 startPosition, Vector3 direction, float totalDistance)
    {
        LR.positionCount = 2; 
        LR.SetPosition(0, startPosition);

        Vector3 currentDirection = direction.normalized;
        int obstacleLayer = LayerMask.GetMask("Obstacle");

        Ray ray = new Ray(startPosition, currentDirection);
        if (Physics.Raycast(ray, out RaycastHit hit, totalDistance, obstacleLayer))
        {
            float remainingDistance = totalDistance - Vector3.Distance(startPosition, hit.point);

            LR.SetPosition(1, hit.point);
            Vector3 reflectedDirection = Vector3.Reflect(currentDirection, hit.normal);
            Vector3 finalPoint = hit.point + reflectedDirection * remainingDistance;

            LR.positionCount = 3;
            LR.SetPosition(2, finalPoint);
        }
        else
        {
            Vector3 endPos = startPosition + currentDirection * totalDistance;
            LR.SetPosition(1, endPos);
        }
    }

This is my method here, the issue can be seen in the video
https://streamable.com/tswd71

Watch "Screen Recording 2025-02-26 at 1.24.51 PM" on Streamable.

▶ Play video
#

When the second line reflects back into the original one and 10* within it, the lines shape is kind of weird, and im unable to find a solution on how to make it consistent

peak summit
#

So I'm having sorta a hard time figuring out the Inventory system for my game.

I need to have the 3 main slots for every other item besides the Headgear & lighter.

This is the inventory code system, (The last 2 images are from the same script)

cosmic rain
tawny elkBOT
peak summit
peak summit
dense estuary
#

I am attempting to implement Sabastian Lagues implementation of Poisson disc sampling, but with a few of my own tweaks. For example, making it so points can't generate too close to the center of the region.
Getting to the point, I am currently trying to figure out how to increase the radius when the points are further away from the center of the region. But I am very stuck on how to do so.

This is my adjusted code:
Poisson Disc Sampling: https://hastebin.com/share/iqeracofat.java
Script that runs/debugs the method: https://hastebin.com/share/amokicupak.csharp

#

Essentially, I want Variable Radii Poisson Disc Sampling, and I currently am using the Bridson Algorithm.

cosmic rain
cosmic rain
foggy pasture
#

heya, is anyone familiar with the "correct" way to attach clothing to a humanoid rig if they aren't part of the same fbx?
I'm creating them all in the same blender file (just for testing) using the same armature, then I export them separately with the same armature, instantiate the clothing on the humanoid model, and set their bones & rootbones to be equal to the humanoid's skinned mesh.

but then I get results like shown, where it seems to be tracking the torso but not the arms..? I can confirm the arms are weight painted correctly & track the armature in blender https://gyazo.com/4b75cf5f5a135074c1bfbff69fb43fd3

#

ignore his hat I turned it upside down by accident

#

and if I apply the bone transfer in editor / not in play mode, it works fine

foggy pasture
#

figured it out, I had a magicacloth component that was breaking when the mesh was having bones swapped (this didn't run in the editor, hence the bug)

peak summit
crimson plaza
#

Would putting [Serializable] on a parent class affect all the derived classes or no?

Also on that note, why is [Serializable] not an option by default? (I currently haven't encountered a case where serializable has not worked)

soft shard
# crimson plaza Would putting [Serializable] on a parent class affect all the derived classes or...

To answer your first question - no it only affects the class it is used on and not derived classes as well, same is true if you used it on a base class and then inherited that base class, it will not also serialized the class that inherited the base

Your second question im not completely certain on why its not a "default" thing, as [Serializable] is often to allow Unity to draw that class to the inspector, and for serializers like Newtonsoft to save/load its data to file, although Newtonsoft doesnt require that attribute to do this so it likely could be "not everything needs to be serialized all the time", though thats entirely a guess

lunar garden
soft shard
lunar garden
soft shard
lunar garden
# soft shard And whats the problem that your having with that? Also what do you already have ...

this is my code so far:
using UnityEngine;

public class LockShackle2 : MonoBehaviour
{
private Animator anim;

private void Start()
{
    anim = GetComponent<Animator>();
    if (anim == null)
    {
        Debug.LogError("Animator component not found!");
    }
}

private void Update()
{
    if (anim == null) return;

    if (Input.GetMouseButtonDown(0) && isMouseOverObject())
    {
        anim.SetBool("isPlaying", true);
    }
    else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
    {
        anim.SetBool("isPlaying", false);
    }
}

private bool isMouseOverObject()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
}

}

lunar garden
#

wrong one

soft shard
lunar garden
#

i posted an image of it tho

crimson plaza
soft shard
# lunar garden i posted an image of it tho

Often code is much better than a image, since you can interact with code far easier than you can interact with a image, and sometimes resolutions can make images hard to read text

crimson plaza
#

It's an attribute

lunar garden
#

`using UnityEngine;

[RequireComponent(typeof(Animator))] public class LockShackle2 : MonoBehaviour
{
private Animator anim;

private void Start()
{
    anim = GetComponent<Animator>();
    if (anim == null)
    {
        Debug.LogError("Animator component not found!");
    }
}

private void Update()
{
    if (anim == null) return;

    if (Input.GetMouseButtonDown(0) && isMouseOverObject())
    {
        anim.SetBool("isPlaying", true);
    }
    else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
    {
        anim.SetBool("isPlaying", false);
    }
}

private bool isMouseOverObject()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
}

}`

#

this is what it looks like now @soft shard

lunar garden
#

it says the script class cannot be found when i try to attach it to my shackle

soft shard
# lunar garden is there a command for code

There is a !code command in this server (forgot about that lol), I think your using 1 backtick, youd want to use 3 for the correct formatting - you can also edit a previous message if you right-click it

tawny elkBOT
soft shard
lunar garden
#

[RequireComponent(typeof(Animator))] public class LockShackle2 : MonoBehaviour
{
    private Animator anim;

    private void Start()
    {
        anim = GetComponent<Animator>();
        if (anim == null)
        {
            Debug.LogError("Animator component not found!");
        }
    }

    private void Update()
    {
        if (anim == null) return;

        if (Input.GetMouseButtonDown(0) && isMouseOverObject())
        {
            anim.SetBool("isPlaying", true);
        }
        else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
        {
            anim.SetBool("isPlaying", false);
        }
    }

    private bool isMouseOverObject()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
    }
}```
#

ah like that

#

look through it and tell me if anythings wrong with it

#

whats causing the class error

soft shard
lunar garden
#

and MonoBehaviour

soft shard
#

Can you show the exact message that your getting when you attach your script?

lunar garden
#

"Can't add script component 'LockShackle2' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match."

#

i decided to add the script to the original but

#

the animation just plays automatically

#

instead of waiting for my clicks

soft shard
lunar garden
soft shard
lunar garden
#

it still dont work

#

ill send you the file and you can help fix it

soft shard
#

If by "send the file" you mean posting the updated code here, sure go for it

soft shard
#

Maybe you can record a video instead, if you think the issue is beyond just looking at the script

lunar garden
#

that didnt work

#

ill send you the animation and basic model

#

and you try to teach me how I was supposed to code it

#

there we go

#

@soft shard

soft shard
# lunar garden that didnt work

Youd have to upload a mp4 for it to show up as a video on Discord, if you think all those files are needed for this issue, its better to record a video showing all your steps and setup, instead of sending files

lunar garden
#

nvm it dont work

#

imma go to sleep

#

you wanna keep working on it tomorrow?

#

i can get on at like 4 pm

soft shard
#

Well this is a public chat, so if you still cannot figure it out next time you work on it, you can always ask your question again, with as much info and relevant visuals, and im sure someone may be able to help if they can - its unlikely many will want to download a file to help though

lunar garden
#

yea fair

#

cya

#

ill dm you just in case

soft shard
#

Thats alright, no need to DM me for this, you can just ask your question here, and if someone can answer they might, doesnt have to be me

peak summit
#

Using this code, whenever I pick up the item it's meant to show that you've picked it up in your hotbar, for some reason whenever I pick up the item it doesn't show the image. Could it be because I'm deleting the item before the sprite takes effect??

https://paste.mod.gg/dlqooijrmgyb/0

kind willow
#

eh... do you have a missing script on a gameobject by any chance?

#

scene or prefab one

peak summit
cosmic rain
peak summit
cosmic rain
peak summit
crisp flower
#

Hey I have this LogStringtoConsole making a lot of garbage and cpus spike, but I can't really see where it's coming from... and what's weird is that i'm not outputting loads to console so I don't really get it.

fervent juniper
#

Hey guys, im having some issues with a line renderer projection

private void LineRendererTrajectory(Vector3 startPosition, Vector3 direction, float totalDistance)
    {
        LR.positionCount = 2; 
        LR.SetPosition(0, startPosition);

        Vector3 currentDirection = direction.normalized;
        int obstacleLayer = LayerMask.GetMask("Obstacle");

        Ray ray = new Ray(startPosition, currentDirection);
        if (Physics.Raycast(ray, out RaycastHit hit, totalDistance, obstacleLayer))
        {
            float remainingDistance = totalDistance - Vector3.Distance(startPosition, hit.point);

            LR.SetPosition(1, hit.point);
            Vector3 reflectedDirection = Vector3.Reflect(currentDirection, hit.normal);
            Vector3 finalPoint = hit.point + reflectedDirection * remainingDistance;

            LR.positionCount = 3;
            LR.SetPosition(2, finalPoint);
        }
        else
        {
            Vector3 endPos = startPosition + currentDirection * totalDistance;
            LR.SetPosition(1, endPos);
        }
    }

This is my method here, the issue can be seen in the video
https://streamable.com/tswd71
When the second line reflects back into the original one and 10* within it, the lines shape is kind of weird, and im unable to find a solution on how to make it consistent

Watch "Screen Recording 2025-02-26 at 1.24.51 PM" on Streamable.

▶ Play video
west lotus
cosmic rain
crisp flower
cosmic rain
# peak summit Wait really?

Don't you see that the gizmos don't align with anything? And the fact that you get negative values for width and height should ring a bell too.

cosmic rain
peak summit
cosmic rain
weak ginkgo
#

i desperately want someone to look at my project and tell me what im doing wrong, its UI something

pine olive
#

I have a question, I am trying to figure out how I can basicly create 2 scriptableObjects then make one a parent or child of the other one, within code.

This is what I have so far:

DrawGrid newGrid = ScriptableObject.CreateInstance<DrawGrid>();

I am using this to create a scriptableObject

//parent the object somehow.

//save using the set path            AssetDatabase.CreateAsset(newGrid, path);
            AssetDatabase.SaveAssets();


I keep scratching my head on this, any help would be great!

leaden ice
thick terrace
pine olive
#

ah ya I think this will work thank you!

pastel halo
#

Hey, how would you go about making a 2D eye follow (UV Offset) work in 3d space?

Like if a character has eyes that are non circular (non-rotatable) and you need to UV offset, but have it follow the target?

Been having difficulty trying to figure out a setup.

Something about setting constraints and then normalizing the distance between the model's "eyeball position" and the look target. Having an anchor for each eye socket, as well as lookat (L/R)

Haven't found much info online since it seems like most folks use regular round eyes and rotation

leaden ice
#

e.g.

Vector2 dirToTarget = targetPos - eyePos;```
pastel halo
#

hmm, i'll give that a shot and see if it works

heady iris
#

Sounds like a trig problem

#

You need to pick a pivot point for the eye, which sits behind the 2D eye texture

#

If the eye mesh is spherical, then use the center of the sphere

#

otherwise, just pick a point that's...kind of where the center of a sphere would be?

#

You then need to know how much angular deflection (so, how much the angle changes) you get by moving from 0.5 to 0 or 1

#

hopefully this thing is radially symmetric, so that [1,0.5] and [0.5,1] have the same deflection

#

you do need to also know which direction the eyes turn in when you change U and V

#

that's a bit fiddly

#

Suppose you now know that:

  • U deflects by 20 degrees on the +Y axis
  • V deflects by 20 degrees on the +Z axis

Given a direction, you need to measure the signed angle between it and the eye's forward vector

#

You'd do so on both the +Y and +Z axes. If the +Y axis angle is -10 degrees, you'll set U to 0.25, since U covers the [-20...20] range

#

I'm not sure if a linear remap is the correct thing to do here

#

you might need to take the cosine of everything first

#

but that's just guessing

heady iris
heady iris
#

So you'd do a maximum positive U offset, put an object there, then repeat for the other three offsets

#

The annoying part here is mapping from a local-space direction to a UV offset

#

(it's almost the exact same problem that i was just describing in #archived-shaders !)

#

just phrased differently

round violet
dire crown
#

Hello, silly question, but how do I check if a gameobject reference set in inspector is a reference to an existing object in the scene (or prefab instantiated) or a reference to a prefab in the Project Explorer?

naive swallow
#

Click once on it and see what gets highlighted

leaden ice
#

errr - is that right? I'm workign off memory here

dire crown
#

let me check that

leaden ice
#

but yeah do you want to know in code or just in the editor

naive swallow
#

Oh, in code, yeah

dire crown
#

In code, yeah 😄

leaden ice
#

I find it odd that you would have a situation where your code needs to dynamically check that at runtime

naive swallow
leaden ice
#

what's the use case

dire crown
#

Basically, there's one object that should be on scene for other scripts to grab at the start. If there's none, it will try to spawn one from scratch. Since this is for a tool, i'm allowing other users to set their own, and i want to support both assigning an already object in the scene as reference or a prefab and then spawning it

#

But im probably just gonna do it another way, wanted to do a quick fix, but better to have it well written

heady iris
#

which generally tells you that it's a prefab

hexed oak
#

Does Unity have a different definition of "loaded" when in context of SceneManager.sceneLoaded ?
I'm seeing in editor and on a built exe that finding an object that only exists in the scene that is supposed to have loaded fails.

The only way I can reliably find this object is if I depend on the AsyncOperation's .completed callback--but nothing in the docs indicates this.
Using 2022.3.38

turbid river
#

hey, i have a problem and im not sure how to fix it
i have a hollow box that moves, and inside it i have a cube
now when the box stops moving, the cube moves (newtons 1st law) and it hits my box and makes it move extra. i do not want that
how can i do it

rigid island
turbid river
#

yeah that didnt work

#

i tried increasing the mass but that didnt seem to help

lean sail
turbid river
#

i think so

#

is there no way to make it just ignore the cube lol

rigid island
#

if its kinematic lol

turbid river
#

grrr hmm

#

but its genuinely not working

rigid island
#

probably easier to fake forces on this kinematic if needed

rigid island
turbid river
#

i see its kinematic and its still getting kicked around by the cube inside

rigid island
#

is this 2d or 3d ?

turbid river
#

2d

rigid island
#

ah..kinematic in 2D works a bit different..

turbid river
rigid island
#

how are you moving the box ?

#

in code

turbid river
#

setting linear velocity

rigid island
#

ahh

rigid island
#

actually iirc it should still work, something is def not set correct on your end

turbid river
#

wdym it should still work

rigid island
#

You shouldn't be able to push a kinematic afaik

turbid river
#

my unity is broken then lol

rigid island
#

for me even at really high mass the dynamics don't do anything to kine
(this is disabled gravity for reds btw and using linearVelocity = vector2.down * speed in fixed update)

turbid river
#

interesting

#

i just dont think this solution will fit well to the project, bc its basically a platformer

rigid island
#

I guess?..you haven't given much info to begin with

worldly stirrup
#

I have a setup where the player can climb slopes, and the gameobject rotates in accordance to the angle of the slope. However, when met in a situation where the player is right on the intersection of 2 different angled slopes, it jitters and rotates quickly between the 2 angles.

oblique spoke
leaden ice
worldly stirrup
# worldly stirrup I have a setup where the player can climb slopes, and the gameobject rotates in ...
        Debug.DrawRay(rb.position,3f*Vector2.up,Color.white);
RaycastHit2D hit = Physics2D.Raycast(checkPos, -transform.up, slopeCheckDistance, whatIsGround);
        Debug.DrawRay(checkPos,-transform.up*slopeCheckDistance,Color.red);
        if (hit)
        {   

            slopeNormalPerp = Vector2.Perpendicular(hit.normal).normalized; 
            slopeDownAngle = Vector2.SignedAngle(hit.normal, Vector2.up);
            transform.rotation=Quaternion.Euler(0,0,-slopeDownAngle);
            isOnSlope=slopeDownAngle!=0;  
            Debug.DrawRay(hit.point, slopeNormalPerp, Color.blue);
            Debug.DrawRay(hit.point, hit.normal, Color.green);
        }```
cursive moth
#

Hi, I have a utils repo that's maintained separately from any projects.
It now requires 2 dlls, Microsoft.Win32.Registry and System.Drawing.Common.
What is the best way to go about including these to avoid possible conflicts?
Have them as listed dependencies in the readme, include them in the utils directory and warn users about it, or does unity just handle these conflicts fine on it's own?
Thanks in advance and please @ me.

leaden ice
solar shard
#

I wanted to code a sort of save state for certain objects in a scene and you could reload them to their initial state on start (transforms, script variables, child objects, components and their variables etc.). Pretty much it's for resetting a puzzle without the need to reset the whole scene. However now that I'm thinking about it, maybe just making a separate prefab of prefabs I can just load is better?

cursive moth
# leaden ice Are you talking about a game or a plugin?

So I have a directory(also a repository) with a lot of utilities I use in almost all my games.
It's a collection of scripts, sprites etc.
I am asking whether the plugins directory(where the 2 dlls I listed are) should be located in NnUtils or just mentioned in the readme that it's needed in order to avoid conflicts with other assets that might include these dlls or maybe even the base project itself.

leaden ice
pearl bay
#

hi! i'm having an issue passing a CSV-ish file through into unity. i'm splitting the string by its commas and putting them into an array via String[] charactersArray = String x.Split(',');

#

it's also getting the returns/line breaks/newlines as a part of the array, which i want to remove. so far, i've tried removing it via regex by trying to trim \r, as well as the standard trim function in String.

leaden ice
#

I recommend simply using an off the shelf CSV parser so you don't have to deal with this nitty gritty stuff.

pearl bay
#

i find it weird that i'm doing exactly what the carriage return is, but it never seems to get removed?

leaden ice
pearl bay
pearl bay
#

see here where the array is storing returns as a part of the character