#archived-code-general

1 messages Β· Page 147 of 1

molten sandal
#

No way, same result

#

something is defenetly broken somewhere

heady iris
#

How is the vehicle moving?

molten sandal
#

smoothly

#

let me check something

heady iris
#

as in, what mechanism is being used

#

a rigidbody? just setting the transform's position?

molten sandal
#

a rigidbody

#

there asre the scripts that controls the ship

heady iris
#

does the rigidbody have interpolation enabled?

molten sandal
#

No

heady iris
#

okay, so that's why the movement looks OK

#

not wildly jittery

#

it's also why the camera is behind

#

the rigidbody moves in the physics update

#

the physics update occurs after FixedUpdate

#

so yes, this is a reasonable thought.

compact spire
#

Have to smooth out the camera motion

heady iris
#

that's a separate matter

heady iris
#

not every physics update

leaden ice
heady iris
#

it basically smears out the movement of the rigidbody over the frames between physics updates

molten sandal
#

So, do I enable interpolate?

heady iris
#

Start by moving that code to LateUpdate and seeing how it looks

molten sandal
heady iris
heady iris
compact spire
#

From a best practice standpoint, should I used my scriptable objects as a direct reference for the monobehavior it's attached to, or should I just use the scriptable object to initialize the values on the monobehavior and don't reference after initialization? Obviously the latter adds additional work but the former requires me to be careful about updating the scriptable object...

molten sandal
#

This same method but in LateUpdate, finally the camera is not left behind, it is always in the same spot relative to the vehicle

heady iris
#

so yeah, it was an order-of-operations issue

#

FixedUpdate runs before the physics system updates

molten sandal
heady iris
#

now you can go back to using SmoothDamp

#

(with a non zero smooth time)

molten sandal
#

There was a reason I didn't use LateUpdate

#

The camera goes wild

#

in LateUpdate

somber nacelle
molten sandal
#

using smoothtime

heady iris
#

you will have to explain.

molten sandal
#

kk

heady iris
#

i am not psychic and i cannot see your screen

molten sandal
#

let me show you

#

one moment

heady iris
#

describe it.

#

i'm guessing that the rotation is bogus

molten sandal
#

Sadly as I said, this CPU is not the best, but some Jitter can be seen in the video

#

Looks like the camera tries to be in two places at the same time

desert shard
#

your smoothsdamp is still instant, isit not?

molten sandal
#

no

#

I gave it 0.1f

#

with higher damping value the jitter is less notisable

#

but it happens with lerp as well

compact spire
#

@somber nacelle There isn't some magical way to apply like 20 data properties to 20 monobehavior properties is there besides line by line right (this is more of a general C# question)?

somber nacelle
heady iris
#

It's very hard to say anything with that janky framerate

#

I'd expect this to happen with a very high framerate

leaden ice
heady iris
#

where there are several camera movements for every rigidbody movement

#

that would make the camera "jump" every time the rigidbody moves

#

Enabling interpolation on the rigidbody would help with that.

molten sandal
#

The game is running at 60FPS but the PC is not powerful enoight to record them

heady iris
#

since it would smear out the rigidbody's movement

molten sandal
somber nacelle
#

right, that's kind of the idea of using cinemachine. you won't experience the problem you are getting from your own code

compact spire
#

@leaden ice Oh, so just have them share the same struct/class?

edgy lynx
compact spire
#

Or I guess that would be a model

molten sandal
hybrid harness
#

How do I 'smooth out' these sharp regions of my generated heightmap?

background context:
the heightmap is generated through a perlin noise, plus a falloff texture ( so the islands never reach the edges )

along with this, Is a voronoi texture using values between [0-1] that determine's the map's "biomes"

a biome is a scriptable object with a 'weight' value and an animation curve to determine the heightmap's multiplier.

the voronoi fragments are assigned a biome depending on its 'weight'

pixels on the texture have their value multiplied depending on the biome its in and its multipler animation curve

somber nacelle
hybrid harness
#

these sharp regions are the borders of the voronoi biome map

peak wing
#

why i cant press button in world space UI?

edgy lynx
# molten sandal Yes I know sorry

It's all good, I understand having some code written already and want to stick with it. But at some point, it's also ok noting that there's a better solution out there that will save you time and headaches. To add to that, Cinemachine is something you will use for nearly every project going forward. So it's not like you're wasting time by picking it up now πŸ™‚

somber nacelle
hybrid harness
molten sandal
hybrid harness
#

but I imagine something to smooth out the heights would have to ignore the heightcutoff of each biome

molten sandal
compact spire
#

@somber nacelle Only if my monobehavior contains those fields/properties though, if I have a myData struct I can just go monobehavior.myData = scriptableObject.myData. I just have to adjust my monobehavior to use myData. I'm guessing struct is probably safest as I don't want to end up with references back to the monobehavior right?

somber nacelle
#

i mean at that point, why even use the scriptable object? why not just serialize the data class/struct directly on the monobehaviour?

heady iris
#

indeed. especially if you aren't going to be "re-using" the data much

hybrid harness
#

the comically large line on line 96 is adjustedHeightMap[x, y] = Mathf.Clamp(currentHeight * biomes[i].heightMultiplier.Evaluate(noiseMap[x, y]), 0, biomes[i].cutoffHeight) - falloffMap[x,y];

heady iris
#

i.e. you aren't going to attach that data to many different things

somber nacelle
# peak wing yes

did you perhaps add screen space UI just now to test it? if so, you should test your world space UI again. you might find that having an EventSystem in the scene suddenly fixes it.
also if that doesn't fix it, then you need to ask in a relevant channel like #πŸ“²β”ƒui-ux instead of a code channel πŸ˜‰

compact spire
#

@somber nacelle Because I would still need a way to apply the struct to the monobehavior in a way that makes sense. But I kind of see your point though.

rose carbon
#

Does anyone know why my instantiated gameobject variables are persistent throughout leaving and entering play mode? I enabled domain and scene reset.
Is there anything else that could cause that behaviour? They only reset once I completely close and start up unity again.

somber nacelle
heady iris
#

mark a struct or class as serializable and it shows up in the inspector.

compact spire
#

Then I'm losing the benefit of scriptable objects

#

hmm

somber nacelle
somber nacelle
compact spire
#

testing changes at runtime?

leaden ice
somber nacelle
heady iris
#

well, you wouldn't be able to change everyone's values at once

#

since they'd either have a struct (value type) or their own instances of the class

somber nacelle
#

sure but their idea was to apply the data from the SO and then no longer be using the SO data anyway

heady iris
#

right

#

so that would be moot

compact spire
#

I guess you can

#

ugh

rose carbon
leaden ice
#

the inheritance thing isn't really relevant

#

you can't call "Use" on the sword class. It's a class. You call Use on an object of that class

#

the question is are you doing it on the prefab version, or the instance

compact spire
#

I kind of built everything around using scriptable objects, sometimes it's hard to plan these things when you haven't designed it before. I hadn't used SO's before so I thought it might be able to makes things easier.

heady iris
#

why do you need to copy the data?

#

if it's read-only, then copying is irrelevant

rose carbon
# leaden ice the question is are you doing it on the prefab version, or the instance

I think I actually did call it on the class, which explains.. things. Not 100% sure yet but I had a reference to the direct Weapon class which is the subclass of every weapon type and a reference to the WeaponObject which is the actual GameObject. Looks like I used Weapon.Use() instead of WeaponObject.GetComponent<Weapon>().Use(), or I should just set the Weapon reference to the Component of the WeaponObject.
tl;dr I think that is actually the issue sir, thank you so much in advance, that thing gatekeeped me for the whole day 🀦

leaden ice
#

unless you have a variable somewhere like Weapon Weapon;

rose carbon
#

I do yea

public Weapon Weapon { get { return _weapon; } set => OnAcquireWeapon(value); }
public GameObject WeaponObject { get { return _weapon.gameObject; } set { _weaponObject = value; } }```
leaden ice
#

Ah - now that's confusing πŸ˜‰

#

Weapon.Use() would be vastly preferred to WeaponObject.GetComponent<Weapon>().Use(), in this case though

#

the latter is just extra useless noise

#

also this:
public GameObject WeaponObject { get { return _weapon.gameObject; } set { _weaponObject = value; } }

#

gives me the heebie jeebies

rose carbon
#

yea I just never set the Weapon to the actual Weapon of the GameObject I created but instead of the reference in the database which is the prefab

leaden ice
#

that property is super busted

leaden ice
#

I would delete _weaponObject and WeaponObject completely

#

those variables are unecessary and confusing

#

Using GameObject references anywhere is almost never the right move tbh

#

unless you just plan on calling SetActive

rose carbon
#

I do plan on modifying its position but I don't think I'll do it outside of the weapon script itself anymore so I dont think there is a need for it anymore

leaden ice
#

you can just as easily do .transform from any component reference as you can from the GameObject reference

rose carbon
#

Yep! Again thanks for the help now and before! Will fix the bugs and hopefully get it working now!

molten sandal
#

Thank you every one for your support guys

#

Cinemachine turned to be best option

#

to avoid headaches

compact spire
#

Perhaps I need to circle back and watch some more tutorials and guides on how to setup these kinds of data structures. For my ship class I was going to use it's prefab to set base values/children/effects, then use a scriptableObject as an offset for an individual ships stats and behavior, then some other sources of changes (level ups, temporary buffs). It makes sense to seperate these data sources out, but as to the "correct way", I guess I need to do more research.

#

One tutorial recommends using a dictionary with a key as an enum to store stats, which I guess solves some issues.. but I wonder if it will introduce others...

cobalt gyro
#
    public static implicit operator ModifiableItem(Item n) => n;```  I'm getting a StackOverflow exception, both of these classes hold the exact same information however Item is a scriptableobject and ModifiableItem has no inheritance
late lion
cobalt gyro
heady iris
#

yeah, you need an explicit conversion in there to break it up.

late lion
zinc parrot
#

is it just me or do normal unity gizmos get unusually slow if you draw a lot of them? why do they get so slow? are they each individual draw calls or what?

grave arch
#

Does anyone here know of any good video or article explaining merging chunks of 2 perlin noise maps?
Similar to what Minecraft is doing where you use maps to make a chunk between two biomes that act as a smoothening element so the chunks doesn't look like different squares stuck together.
I'm just doing it in 2D right now however.
The problem is basically that I want the surface to have less caves while the terrain under it is a bit more cave like.
Been trying to find this online but just keep finding these videos for basic generation.

late lion
zinc parrot
#

couple thousand

quartz folio
zinc parrot
#

oooo this looks useful thanks!

quartz folio
#

(text in my package is really slow as it's just IMGUI, but it doesn't exist in default sooooo)

compact spire
#

Why would you need that many gizmos active at any given time?

quartz folio
#

For me, I am using Entities and my authoring scene is mostly gizmos, only at runtime does my game spawn graphics

warm oasis
#

are you optimising a networked server or are you trying to optimise editor ?

dense estuary
#

If i want to make a physics based movement script would it be better to set RigidBody.velocity manually or use RigidBody.AddForce() and make counter movement so the player doesnt slide around?

somber nacelle
#

well first you'll want to set up drag on the rigidbody

dense estuary
#

alright.

somber nacelle
#

if you want more control over it then you'll also want to add some counter forces. but simply starting off with some drag will help prevent the infinite sliding

dense estuary
somber nacelle
#

this should be moving relative to the direction this object is facing

#

but also you could instead just use AddRelativeForce instead of transform.TransformDirection inside of AddForce

dense estuary
#

transform.rotation = Quaternion.Euler(0, Camera.main.transform.eulerAngles.y, 0);

somber nacelle
#

then your movement should be correct with the direction the camera is facing. provided your player is actually rotating with the correct camera

dense estuary
somber nacelle
#

you should have been getting a NullReferenceException. don't ignore the errors in your console

dense estuary
#

Alright, I have encountered another issue, i think adding drag caused me to be unable to jump.

somber nacelle
#

oh you're using the default forcemode for your jump instead of ForceMode.Impulse

#

oh and for the love of god cache the reference to the GroundCheck object instead of calling transform.Find every frame

dense estuary
somber nacelle
#

yes that is better

dense estuary
#

Alright, thats good.

#

thank you

stable osprey
#

what's wrong?

dense estuary
somber nacelle
stable osprey
#

and also you seem to be adding vertical force every frame equal to the current velocity

dense estuary
somber nacelle
stable osprey
#

the whole line 24 of your script is very dubious :p

dense estuary
stable osprey
somber nacelle
#

can you show what the code currently looks like?

dense estuary
somber nacelle
#

you're still adding the rigidbody's Y velocity in your AddRelativeForce call

dense estuary
#

Oh, alright, its better now. I am having one other issue though. The camera is randomly moving in the direction you turn really fast and then stopping.

night harness
#

Anyone know off-hand if cameras render renderers that are 100% transparent?

#

Like a cube with 0 opacity, is that still actually rendered or does unity see that its invisible and skip it

dense estuary
dense estuary
somber nacelle
#

forces in the opposite direction

shrewd plume
#

Does someone can help me with this bug ocurring on the LTS 2022.3.4 version of unity, it seems to be happening when going on prefab context mode with the gray background, the other options doesn't seem to be affected by this problem

somber nacelle
#

if it's a !bug with the editor that you can consistently reproduce then you'll want to report it πŸ‘‡

tawny elkBOT
#

πŸͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

πŸ“ If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click β€˜Report a problem on this page’!

πŸ’‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

somber nacelle
#

also this is a code channel

dense estuary
shrewd plume
#

Yes sorry, I've just sent it because I couldn't find other related channel...

#

but thanks! I'll ask there!

dense estuary
weary socket
#

Hi there everyone, I'm working on an FPS project of mine, and right now I'm getting the fundamentals set up. I want this to have multiplayer compatibility, to do this I am sending 'packets' of relevant info, such as where you're looking, where you're moving, etc., to the server from the client. The problem I'm having is that when I try to send the packet from the client via my method: MoveProcessor.SendPacket(Packet2Send);A CS0120 error is appearing. A solution that is often presented online is to do something like: var MP = new MoveProcessor();``````MP.SendPacket(Packet2Send);
This solution resolves the error, but I am afraid it will enable cheating far easier, as this would be creating a copy of a thing on the server on the client.
SendPacket is a method in the MoveProcessor class, that itself is within a namespace that is taken care of by having a 'using' at the top of the client script. I am willing to send any more information needed. Help would be greatly appreciated.

shell scarab
#

is there a faster way to do this operation?

Vector2 upOne = new Vector2(0, 1);

Vector2.Lerp(Vector2.Lerp(Vector2.zero, upOne, value), Vector2.Lerp(upOne, Vector2.one, value), value).y;
quartz folio
#

If you only need the y coordinate, don't lerp the entire vector

#

if you are lerping between 0 and your value, that's just a multiplication (value must be between 0 and 1)

mellow sigil
#

and lerping between 0 and 1 is just the value (clamped to 0-1) and lerping between 1 and 1 is just 1

shell scarab
quartz folio
mellow sigil
#

I think the lerp is equivalent to just (1 - value) * value + value

#

when value is between 0 and 1

shell scarab
#

yea that's pretty close fs, maybe I'll just replace it with that. or (value-1)^3 + 1 might also work for my case

weary socket
#

Calling a non-static method without creating a copy

next sparrow
#

Hello, I'm having a weird issue with materials assignment on my mesh renderer.

#

I have a simple List containing the same material twice

#

Only 2 materials in the list

#

I assign this list (after transforming to array) to the skinrenderer

#

Then I check the instanceId of before and after

#

The two first line are from my materials list which contains twice the same materials as expected. The two last lines are from the skinrenderer which seems to duplicate my material array ??

leaden solstice
next sparrow
#

Oh I was not aware of that. But isn't there a way to not duplicate if it's the same instanceid?

#

I don't mind if it creates a new one but I don't get why it creates it twice if it's the same instance.

leaden solstice
#

Because it copies individual element

mellow sigil
#

If the renderer has two materials they're separate instances and therefore have unique IDs, even if they're the same material

leaden solstice
#

There is Renderer.sharedMaterials but you'd need to manage it well

next sparrow
#

I need it to be not shared.

#

But this is really weird. I'm pretty sure I remember not having this issue before

#

Because I want only one material here instead of two. It's the same cloth, I don't need two.

#

How can I have only one material here despite the materials array requiring 2 elements ?

mellow sigil
#

Nice XY problem

next sparrow
#

I do remember having it only once before. that's so strange.

#

XY problem ?

mellow sigil
#

Where does the two element requirement come from?

next sparrow
#

A faulty model.

#

Which I can't change

next sparrow
#

So there is no way to not duplicate the material? No way to keep the original material?

stable osprey
#

or to be more explicit renderer.material = new Material(someMaterial);

next sparrow
#

My new material array contains twice the same material and when I assign this to the renderer, it creates two distinct copies instead of only one copy so I end up with 2 different materials instead of only one.

#

I want something like
materials[0] = mat1; materials[1] = mat1;

#

I want the same material on the renderer

#

It's possible to do that through the editor

#

Why not at runtime?

stable osprey
#

it can't be both not shared and shared at the same time ;P

#

I was going off this but seems you actually want shared materials, then

next sparrow
#

But sharedMaterials means if I have another model like this one, it will also use this shared material ?

#

Meaning if I have a red dress and I spawn another I want blue, it will make them both blue if I use sharedMaterials, doesn't it ?

stable osprey
#

shared material means single instance -- not duplicates

#

however, you will never be able to change the values of a shared material via the inspector in runtime

#

meaning if you have a material for red dress you can use it to spawn X red dresses. And when you change the color on that material to purple, all red dresses become purple

#

the change just has to happen via code, because the inspector does not support this

lethal rivet
#

I'm getting an error on the line with the comment, I didn't know Events even had to be initialized

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public delegate void ValueChangedHandler();
    public event ValueChangedHandler ValueChanged;

    Dictionary<StatType, float> gameStats;
    public Dictionary<StatType, float> GameStats
    {
        get { return gameStats; }
        set
        {
            gameStats = value;
            ValueChanged(); // Error here
        }
    }```
Error: `NullReferenceException: Object reference not set to an instance of an object`
`GameManager.set_GameStats (System.Collections.Generic.Dictionary'2[TKey,TValue] value) (at Assets/Scripts/GameManager.cs:37)`
`GameManager.Start () (at Assets/Scripts/GameManager.cs:58)`
#

I don't know how to get around this

lethal rivet
#

So Events are objects? Also thank you!

ashen yoke
#

its a delegate

stable osprey
#

kinda πŸ˜„

ashen yoke
#

its an object yes

lethal rivet
#

Ahh I need to google what delagates are before asking dumb questions haha

ashen yoke
#

delegate is just an array of method pointers, essentially, wrapped in very heavy syntax sugar

lethal rivet
#

Hmm

ashen yoke
#

so when you code you get things like del()

#

anyway here a very good playlist

stable osprey
#

yes pls

ashen yoke
stable osprey
#

was hoping music

lethal rivet
#

Jamie King, the man the myth the legend πŸ™ πŸ™ πŸ™

#

Okay so a delagate is basically just like a shorthand of a class with syntax sugar

ashen yoke
#

think of it just as object that has references to methods that match the declared signature

#

it cant be "just" a class because the ability to keep method pointers is reserved exclusively for delegates

#

you cant create a normal class that does the same

#

the only way to simulate what compiler does is by using reflection

#

which is not the same as what delegates do

#

so it sorta is just a class, but isnt

lethal rivet
#

I see

#

Thanks for the breakdown

eager cliff
#

is it possible to fade out a particle system without changing its duration or using color over lifetime by code? I want to fade a particle system in the middle of its playtime. (eg. when player do something, it interrupt the boss skill and make it dissappear but setting it unactive directly seems odd, how to make it fade out?)

ps: the particle itself can fade out normally if using color over lifetime. However, I cant adjust the duration of it when its playing so it cant do the "interrupt" effect.

lethal spire
#

Hello guys, need some help, I've got a scipt made only for the unity Editor, witht he decorator [InitializeOnLoad]. The point is just to have a little comfort so that when I hit the play button, the editor always loads my first scene regardless of the scene I was editing. and that when I exit play mode, it loads back the scene I was editing.

My script almost work but for some reason I can't get back to the scene I was editing before playing. My error comes from the fact that while watching the " EditorApplication.playModeStateChanged" the event " PlayModeStateChange.ExitingEditMode" is never fired, while all the others (EnteringPlayMode, ExitingPLaymode, EnteringEditMode...) are fired. Any clues or usefull links ? I am a bit lost :/

stable osprey
#
  • I can answer but can't read your question πŸ˜›
lethal spire
stable osprey
#

hastebin

lethal spire
#

Line 21, I can see all the event fired but "PlayModeStateChange.ExitingEditMode". Yet My editor does load me on my InitLoading scene. It's very confusing

stable osprey
#

cool! need 3'

lethal spire
#

Thx!

lethal spire
#

It does

stable osprey
#

well that's what should happen, no?

lethal spire
#

It should, but sceneBeforePlay is null

#

Line 31, 32: I don't see any Logs in my console, yet I am being loaded into InitLoading scene

stable osprey
#

so it says.. Loading previous scene: (empty as null), and then it loads some scene?

lethal spire
#

if I comment line 33, that loads the scene, it stops loading me in the InitLoading scene. So it is 100% this line is called, but the two before aren't working at all

stable osprey
#

also, you should make sceneBeforePlay = ""; after loading to have it be safer

lethal spire
#

Uh. I found a solution that is working

stable osprey
# lethal spire Hello guys, need some help, I've got a scipt made only for the unity Editor, wit...

ok I've read the last bit.. I had noticed this at some point as well, I made a hack:

EditorApplication.playModeStateChanged += OnPMChanged;

void OnPMChanged(..) {  if (state == EnteringPlayMode) { EditorApplication.update += WaitUntilPlayModeExit; }  }
void WaitUntilPlayModeExit() {
  if (EditorApplication.isPlaying) { return; }
  EditorApplication.update -= WaitUntilPlayModeExit;
  // run code you want
}
lethal spire
stable osprey
#

iirc in my case the need was something related to editing variables on all scenes, so wasn't using playModeStateChanged at all.. but you don't really need it anyway since u have update

ashen yoke
#

there is built in way to override play scene

stable osprey
ashen yoke
#

EditorSceneManager.playModeStartScene

lethal spire
stable osprey
#

what's the word.. annoying? πŸ˜›

#

I suggested just adding a bool that turns it on/off whenever you want, so it wouldn't need code commenting when you didn't want it at some point

lethal spire
stable osprey
#

maybe in project settings or a keybinding

ashen yoke
#

i think yes

#

because i dont see any code that stores opened scene anywhere

#

only setting it to null on ExitPlaymode

lethal spire
stable osprey
#

alternatively you could work with adding this to an object on the editing scene:

public class SceneRelayLoader : MonoBehaviour {  void Awake() => EditorSceneManager.OpenScene("Assets/Scenes/InitLoading.unity"); }

and once you exit play mode the original scene would be loaded again, as default behaviour

ashen yoke
#

in any case if you need to store state between domain reloads use SessionState/EditorPrefs

#

you can get any asset guid and set as string

lethal spire
stable osprey
#

if you feel it should be default behaviour then yeah πŸ˜„

#

I like prototyping gameplay on separate scenes quite often -- minigames, UI behaviours or whatever.. quicker loading times

lethal spire
lethal spire
ashen yoke
#

AssetDatabase.LoadAssetAtPath<SceneAsset>(assetPath)

lethal spire
#

Lmao

#

From 50 lines to :

   static ForceSceneUnityEditorOnly()
    {
        Debug.Log("ForceSceneUnityEditorOnly: InitLoading");
        SetPlayModeStartScene("Assets/Scenes/InitLoading.unity");

        // EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
    }
#

It works like a charm; thanks guys

ashen yoke
#

keep playmode changed hook

#

clear start scene in ExitingPlaymode

stable osprey
#

why so?

lethal spire
#

Yeah, why ? :o

ashen yoke
#

because if you dont it is stuck on that scene until domain reload

#

you open other scene press play it loads the one you set instead

stable osprey
quartz folio
stable osprey
#

right, fixed

lethal spire
lethal spire
ashen yoke
#

create editor window class, shove in it all functionality you need, keep it open

stable osprey
#

I can press ctrl+Z/ctrl+S in editor and not hear BEEP sounds

lethal spire
#

That's many concept I never heard of yet

stable osprey
#

technically could restore to Default instead of custom Editor Default (... I think)

stable osprey
jovial moon
#
public Mesh createMesh(List<Vector3> vertices, float thiccness, float offset)
{
    Mesh mesh = new Mesh();
    float topHeight = thiccness * (offset+1);
    float botHeight = thiccness * offset;
    //Set the vertices
    Vector3[] meshVertices = new Vector3[6];
    meshVertices[0] = vertices[idA] * topHeight;    //A Top
    meshVertices[1] = vertices[idB] * topHeight;    //B Top
    meshVertices[2] = vertices[idC] * topHeight;    //C Top
    meshVertices[3] = vertices[idA] * botHeight;    //A Bot
    meshVertices[4] = vertices[idB] * botHeight;    //B Bot
    meshVertices[5] = vertices[idC] * botHeight;    //C Bot
    mesh.vertices = meshVertices;
    int topMeshChannel = 0;
    int botMeshChannel = 1;
    //Triangles
    int[] topTriangle = new int[3]
    {
        0, 1, 2,    //Top
    };
    
    int[] botTriangle = new int[3]
    {
        5, 4, 3     //Bot
    };
    mesh.subMeshCount = 2;
    mesh.SetTriangles(topTriangle, topMeshChannel);
    mesh.SetTriangles(botTriangle, botMeshChannel);
    
    //UV
    Vector2[] topUV = new Vector2[6]
    {
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1),
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1)
    };
    Vector2[] botUV = new Vector2[6]
    {
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1),
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1)
    };
    // mesh.SetUVs(topMeshChannel, topUV);
    mesh.SetUVs(botMeshChannel, botUV);
    
    // Return the created mesh
    return mesh;
}
#

Any idea why my bottom mesh doesn't have a UV?

#

If I uncomment // mesh.SetUVs(topMeshChannel, topUV);, both of them have a UV

#

I want the top and bottom to have individual textures and UVs

stable osprey
#

channel is not subMeshIndex

#

it's just a property used by shaders

#

just combine the UV arrays sequentially and pass them to channel 0, since that's what your shader seemingly uses

#

also the var names here are misleading.. they should be botSubmeshIndex/topSubmeshIndex

#

you usually wanna do mesh.SetSubMesh as well in those cases, but not sure if it does have a difference over SetTriangles(tris, submeshIndex) & mesh.subMeshCount =

jovial moon
#

I renamed them to the correct ones now, thank you!

jovial moon
#

Doesn't seem to be doing it :c

#

Maybe my approach is bad.

#

I'll draw what I am trying to do

#

This is the general shape of what my extruded triangle will look like

#

I want the top to use one texture, sides each individually the same texture, and then the bottom a unique texture also

#

I can make the the individual submeshes no problem

#

But the UVs are what don't work for me :c

quartz folio
#

Have you referenced this asmdef from yours?

stable osprey
quartz folio
#

Hrm, looks fine. I usually override references and reference plugins manually to have more control

stable osprey
#

Auto-referenced is only Auto-referenced by UnityEngine.dll, not ALL your assemblies

#

you need to manually reference the asmdef that contains the attribute from all assemblies that need to use it

#

maybe it's not an asmdef then

#

and you're trolling

#

yeah this doesn't look like asmdef, just dll (?)

jovial moon
#

I just need a way to have 3 different textures on my mesh - one on top, 3 of another on sides, and 1 on the bottom

#

Different materials would be nice though, thinking about it.....

#

I already assign it a Material[5] for each of the faces

stable osprey
#

if it's a DLL, you'll need to 'override references' on the asmdefs that need it, and manually select it from the dropdown

jovial moon
#

And they do work, but the UVs are always only from the first index and I don't get why

#

I just need to separate out the UVs for the faces...

stable osprey
jovial moon
#

I need to be like: For the top, the 3 vertices have these UV coordinates. For side A, the 4 vertices have these UV coordinates.

stable osprey
#
Vector2[] PackUVs(params Vector2[][] uvs) {
  List<Vector2> packedUVs = new();
  for (int i = 0; i < uvs.Length; i++) {
    foreach (var uv in uvs[i]) { packedUVs.Add(uv / (uvs.Length - i)); }
  }
  return packedUVs;
}

(this is actually wrong.. uvs should be offset instead)

jovial moon
#

So this would put all 3 textures into one, for UV use?

stable osprey
#

@jovial moon this is usually how it happens so a single texture will be needed πŸ˜› but.... not sure how to make it accept 3 textures..
I always assumed the thing I posted above would be the way

jovial moon
#

Hmmm that's very interesting, although thinking about it - the material approach would be better for me!

#

I can already assign a different material for each of the faces

#

My issue being that they All follow the same set of UV coordinates :c Even if I define them by their corresponding index

#

Would you have any idea how to tell which index should use which UV?

stable osprey
#

are you familiar with shaders?

jovial moon
#

To a small degree, but would love to learn more! I've done some GPU rendering on a Compute Shader before, and some node based shader stuff in Blender!

stable osprey
#

Oh, nice! Well it's pretty much the shader's job to tell which UV should be used.
CPU sends in some local data like this:

#

and the shader uses it to map it to the appropriate texture with this:

#

as to how to make it work with just the Unity Standard Material/shader.. no idea, really πŸ˜„

#

let me take a deeper look tho

jovial moon
#

I see so I will need a shader most likely, that works! Thank you!

open glen
#

How do i correctlly set the color of spriteRenderer with a script? I use a script that just directlly sets .color to the color I want and I'm pretty sure thats how it always worked for me. But when I do it now it doesn't update the color. But the rgb values in the component are correct. When I change them in the editor it works fine. I'm really confused, looks like a bug to me, but i could just miss something obvious.

stable osprey
#

And this didn't work?

    Vector2[] UVs = new Vector2[12]
    {
        // Top vertices
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1),
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1),

        // Bot vertices
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1),
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1)
    };
    mesh.SetUVs(0, UVs);
stable osprey
#

so vertices[5] should be using uvs[5]

stable osprey
#

so yeah realized I might not be the best one to help with submeshes πŸ˜„

prime fossil
#

what do ppl here feel about usage of Invoke and InvokeRepeating?

#

I've read few forum posts with very polarized views

thin aurora
#

They have their niche use

#

The only downside they have is fixable with nameof()

prime fossil
#

like how coroutines do it

thin aurora
#

Coroutines don't pass an Action, you invoke the method and StartCoroutine will iterate all the returned yield instructions

#

But I know what you mean, I guess Action wasn't a viable option when they made it

prime fossil
#

would be cool if they updated it

thin aurora
#

The latter would be an action, or actually delegate

prime fossil
#

I recall doing it as latter

#

bad memory i guess

thin aurora
#

Nah, StartCoroutine accepts an IEnumerator, which is what your Coroutine function returns

#

You get the idea

prime fossil
#

yeah

thin aurora
#

You can probably make your own Invoke extension though

prime fossil
#

I wonder if any unity devs can explain why invoke is (still) reflection based tho

prime fossil
thin aurora
#
class NewMonoBehaviour: MonoBehaviour
{
  protected Invoke(Action @action, float time)
  {
    StartCoroutine(this.CoroutineActionInvoker(@action, time));
  }

  private IEnumerator CoroutineActionInvoker(Action @action, float time)
  {
    yield return new WaitForSeconds(time);
    @action();
  }
}
#

Something like that

prime fossil
#

could also add cancelinvoke

#

and repeating

thin aurora
#

I'll do you one better

prime fossil
#

oh?

thin aurora
#
class NewMonoBehaviour: MonoBehaviour
{
  protected Invoke(Action @action, float time, CancellationToken cancellationToken = default)
  {
    StartCoroutine(this.CoroutineActionInvoker(@action, time, cancellationToken));
  }

  private IEnumerator CoroutineActionInvoker(Action @action, float time, CancellationToken cancellationToken)
  {
    yield return new WaitForSeconds(time);
    if (cancellationToken.IsCancellationRequested)
    {
      yield break;
    }

    // Alternative, although this throws (which basically everything does when they use CancellationToken things).
    //cancellationToken.ThrowIfCancellationRequested();

    @action();
  }
}
prime fossil
#

wait

#

you can pass cancellation tokens to coroutines?

#

wild

#

oh wait no

thin aurora
#

You usually only use cancellation tokens with asynchronous methods, but the idea is cancelling delayed processes, which fits under this

prime fossil
#

Its your method

thin aurora
prime fossil
#

reading code in discord is painful KekDoggo

thin aurora
#

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

prime fossil
#

yeah yeah I know

#

discord is just being annoying

#
  private IEnumerator ActionRepeatingInvoker(Action @action, float time, CancellationToken cancellationToken)
  {
    while(!cancellationToken.IsCancellationRequested){
      yield return new WaitForSeconds(time);
      @action();
    }
    yield break;
  }
#

you can make repeating too

#

neat

#

didn't test this code fyi

#

wrote it on the fly

thin aurora
#

Yes this works

#

You don't need the yield break;

prime fossil
#

habit

#

I always put it at the end

thin aurora
#

Enumerators are nice when you get the hang of it

prime fossil
#

hmm I feel like if it is this easy to make it work with actions surely there is a reason unity devs haven't done it

prime fossil
thin aurora
#

You can also make custom stuff if you know how, and recursion is way easier

prime fossil
#

recursion itself is sometimes like shooting yourself on the foot

#

I had far too many bad memories using it

thin aurora
#
private IEnumerator<int> _myInfiniteEnumerator;
private int interval = 0;

private void Awake()
{
  this._myInfiniteEnumerator = this.MyInfiniteEnumerator().GetEnumerator();
}

private void Update()
{
  this.interval += Time.DeltaTime;
  if (this.interval > 1)
  {
    this.interval = 0;
    
    _ = this._myInfiniteEnumerator.MoveNext();
    Debug.Log(this._myInfiniteEnumerator.Current);
  }
}

private IEnumerable<int> MyInfiniteEnumerator()
{
  var i = 0;
  while(true)
  {
    unchecked
    {
      yield return ++i;
    }
  }
}
#

This logs a number every second, forever

#

Have fun

prime fossil
#

aren't those this's redundant?

#

they're are in same class

thin aurora
#

Yes, I'm used to doing it

prime fossil
#

Js dev?

thin aurora
#

My code configuration forces it, and I am indeed a typescript developer

prime fossil
#

aha!

#

yeah I can see why

thin aurora
#

So this can literally go on forever, no matter what

prime fossil
#

its all psudo code anyway

thin aurora
#

No you can really put this in a MonoBehaviour and it will work

#

Try it

prime fossil
#

since floats and doubles are not 100% precise

prime fossil
thin aurora
thin aurora
#

Might even make it worse

prime fossil
#

I don't think so

thin aurora
#

I'm not checking a precise number so it would not matter

ashen yoke
#
    private float lastTick = 0;
    private const float tick = 0.1f;

    private void Update()
    {
        if (lastTick + tick < Time.time)
        {
            lastTick = Time.time;
            _ = this._myInfiniteEnumerator.MoveNext();
            Debug.Log(this._myInfiniteEnumerator.Current);
        }
    }
#

pls

prime fossil
#

since deltatime will be different every update

#

there is probably more room for error

ashen yoke
#

also need to carry over the remainder

thin aurora
ashen yoke
#
    private float nextTick = 0;
    private const float tick = 0.1f;

    private void Update()
    {
        float time = Time.time;
        if (nextTick < time)
        {
            float remainder =  time - nextTick;
            nextTick = time + tick - remainder;
            _ = this._myInfiniteEnumerator.MoveNext();
            Debug.Log(this._myInfiniteEnumerator.Current);
        }
    }
thin aurora
#

The most accurate timer is one that uses Time.DeltaTime to adjust itself

#

Coroutines are very imprecise

#

Because WaitForSeconds is never truly the amount you give it

thin aurora
#

Unity does a lot of stuff around it, so it will force the delay to be longer. The more instructions, worse the delay

#

Time.DeltaTime does not have that, it gives the soonest moment that it passes the delay in my case

prime fossil
#

there is time to execute and every electronic device has imperfections

ashen yoke
#

never use delta time for accumulation

#

there is next tick pattern which is better in every way

prime fossil
#

isn't deltaTime time between current and last frame anyway?

ashen yoke
#

no, its some average

#

2 last frames taken into account

prime fossil
#

oh?

late lion
prime fossil
ashen yoke
#

its incorrect

late lion
#

Do you have a source for that?

steady moat
#

Time.deltaTime returns the amount of time in seconds that elapsed since the last frame completed. This value varies depending on the frames per second (FPS) rate at which your game or app is running.

ashen yoke
prime fossil
#

its a gif 😭

#

oh well

prime fossil
#

could you be talking about smoothDeltaTime or something?

steady moat
prime fossil
#

yeah I feel like thats what they're talking about

#

it seems to smooth out the difference over time

#

rather than do it instantly

thin aurora
#

What you're doing is basically determing what Time.DeltaTime is, and storing that seperately

ashen yoke
#

because there wont be float math error accumulation every frame happening

prime fossil
#

aha

#

what I was worried about as well

ashen yoke
#

if you run 2 timers for a very long time, the one that accumulates delta will be off

thin aurora
#

That's true, you do have the drawback of that

steady moat
#

A very long time

ashen yoke
#

the tick with carrying reminder over also suffers from that but the error accumulation is much slower

ashen yoke
#

i encountered this when i was making a train sim with time acceleration

prime fossil
ashen yoke
#

classic x4 x16 speed

prime fossil
#

I think forever is a very long time

late lion
# steady moat

You can see above, on frame 8, that unscaledDeltaTime (d) and deltaTime (e) differ in how much time they report has elapsed. Although a whole second of real time elapsed between frames 7 and 8, deltaTime reports only 0.333 seconds. This is because deltaTime is clamped to the maximumDeltaTime value.
I didn't know this. This would make Time.deltaTime not suitable for accurate time keeping, unless you increase maximumDeltaTime

prime fossil
#

just use decimal trollface

steady moat
#

Use a start time instead.

late lion
#

You may need to in some cases, such as if your timer needs to pause or have a different time scale than Unity's.

steady moat
#

No, you can still use a start time.

#

Just accumulate between pause.

prime fossil
ashen yoke
prime fossil
#

I'm glad you've fact checked it though Heart

#

mistakes happens to best of us

thin aurora
#

My method only has the precision issue that adds up every frame, as mentioned before

#

So both have their drawbacks
(I specifically added an unchecked call in my code to make sure that it will in fact run forever, fyi πŸ˜‰)

frozen hemlock
#

I am using Unity Visual Scripting and working on a simple Quiz game. Now I would like to get the Questions / Answers and Correct Answers from a JSON file. I find tutorials about it in c# but can't seem to get it working in Visual Scripting. Is this possible? Anyone knows how to do this?

leaden ice
late lion
frozen hemlock
#

I prefer Visual Scripting. I have a designer background and really like it this way.

thin aurora
#

They're both still better than Coroutines πŸ˜„

prime fossil
#

if you can read files with visualscripting

#

CSV's layout would be way easier to work with

#

than JSON

leaden ice
#

you shoukldn't be "working with" either one

#

just feed it through the parser

prime fossil
frozen hemlock
#

how do I feed it trough the parser?

leaden ice
frozen hemlock
potent sleet
potent sleet
#

you need FromJson and get the object

prime fossil
#

ToJson would make it to a json type

leaden ice
#

(you'd also have to have defined such an object)

prime fossil
#

yeah you're looking for from

#

I honestly love using newtonsoft's json linq library for json stuff

leaden ice
#

IDK Visual Scripting is adding such an unecessary layer of complication here

prime fossil
#

makes it feel more like JS way of doing it

potent sleet
#

ikr this would be a one liner

prime fossil
#

I mean if they want to

#

let em I say

leaden ice
#

I think it would be easier to learn C# than to get JsonUtility.FromJson working in Visual Scripting

prime fossil
#

C# and JSON work weirdly

leaden ice
#

mostly because a C# class/struct needs to be defined to receive the data

prime fossil
#

^

#

I'm getting absolutely clowned on πŸ’€

potent sleet
#

it's a questionalble statement

prime fossil
#

okay then

#

why is it not?

potent sleet
#

huh ? JSON is just a special text file. C# handles text files just fine

prime fossil
#

tbf at that point anything is a special text file

leaden ice
#

yes indeed

prime fossil
#

no like I want to know why

leaden ice
#

why what

#

there is no "weird" interaction specifically between C# and JSON

#

you might think that the way some particular JSON library handles things is weird, but that has nothing to do with C#

#

C# doesn't actually know or care about JSON in particular

frozen hemlock
prime fossil
#

please

frozen hemlock
#

i know I am already in that discord. but that discord is quite death

potent sleet
frozen hemlock
#

response time is a day or so

potent sleet
#

not a lot of people use visual scripting as much

prisma birch
#

Does anyone know of a way to exclude certain assets from the asset picker? For example, VFX Graph creates all of these "hidden" materials that are of no direct use to me and they are polluting up my options.

leaden ice
#

not really a code question...

frozen hemlock
late lion
leaden ice
potent sleet
#

you need to tell the parser how your json object is "structured"

prisma birch
prisma birch
late lion
frozen hemlock
#

but I guess I have to do it like this?

potent sleet
#

also your json is prob wrong,
you need to make the answers strings

leaden ice
frozen hemlock
potent sleet
#

no clue how would you use it inside of visual scripting tho

#

you need a "template" to modify your json file

#

or read it

leaden ice
potent sleet
#

ahh it doesn't ? that blows.. I never use it , i use json.net

leaden ice
#

also probably better to just use an array for the answers rather than numbered variables

potent sleet
#

very true, i just copied their json into the converter :p

ashen yoke
#

you can use newtonsoft, it has JObject

#

which is basically a dictionary with strings

leaden ice
#

yeah that's probably better to use with visual scripting

potent sleet
#

newtonsoft is amazing

leaden ice
#

because defining a class is ??? in VS

frozen hemlock
#

this is basicly the idea I had. that is the INT = 1 then that is the correct answer.

leaden ice
#

if you want this, it's a custom format

frozen hemlock
#

and somehow substract this data from a text file

#

no i know

#

this is just simply explained

leaden ice
#
{
  "Question": "What is unity",
  "Answers": [ "Game Engine", "Tea Party", "Shopping Mall" ],
  "CorrectAnswer": 0
}``` this would be one way to do it in JSON
frozen hemlock
#

thanks and 0 becouse it is the first one in the list?

leaden ice
#

yes

frozen hemlock
#

but I am not even close to this proces. I don't even know how to read this data in Visual Scripting

#

which nodes to use

leaden ice
#

using JObject as mentioned above would be an easyish way

frozen hemlock
ashen yoke
#

its a c# library

potent sleet
ashen yoke
#

if it reflects yes

worn badger
#

Library\PackageCache\com.unity.inputsystem@1.4.4\InputSystem\Utilities\PredictiveParser.cs(92,64): error CS0433: The type 'ReadOnlySpan<T>' exists in both 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

how on earth can i fix this?

#

i even deleted and reopened a backup of the project without this issue

#

and it still persists

ashen yoke
#

you understand what the error says?

worn badger
#

Not really? I dont know what System.Memory is and i dont know why this came out of nowhere

ashen yoke
#

it says that two identical assemblies are in use, one probably comes with some package, other may be from some asset you use

#

i dont understand how ReadOnlySpan<T> can be in .net standard tho

worn badger
#

me either

#

im at a total loss as what to do lmao

late lion
leaden ice
worn badger
#

Ill try that.

thin aurora
frozen hemlock
#

haha vind het fijn werken

thin aurora
#

But in all seriousness, try to stay away from JSONUtility

#

It's very limited and it won't help you in any way if something goes wrong

worn badger
worn badger
#

so the version isnt the issue im sure

#

this happened when i reloaded a solution

worn badger
#

going to reinstall visualstudio and dotnet

#

last thing that i can think would fix it

steady moat
#

I relly doubt it would fix your issue

#

What is the full message ?

worn badger
#

Library\PackageCache\com.unity.inputsystem@1.4.4\InputSystem\Utilities\PredictiveParser.cs(92,64): error CS0433: The type 'ReadOnlySpan<T>' exists in both 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

gray mural
#

Is there someone good at maths? How do I make from numbers on the left side numbers on the right side?

-4  => -7
-3  => -5
-2  => -3
-1  => -1
 1  =>  1
 2  =>  3
 3  =>  5
 4  =>  7
#

with just maths

steady moat
gray mural
steady moat
#

Because you can do something with just those numbers, but it will not have a logic.

weary rose
#

is there like a general help?

gray mural
weary rose
#

i need help with using the ml agents package

weary rose
#

thanks

gray mural
#

if value + 1 == text then currLine should be += 1

#

if value - 1 == text then currLine should be -= 1

#

otherwise is just jump more

#

like if value + 2 == text then currLine should be += textLineCount + 1

jovial moon
crimson summit
#

now that i have a button, how to configure it so when i press it a new interactable panel should spawn

jovial moon
#

The issue is that they all share the same UVs

#

I can't give each individual face a full rectangle texture

#

Some of the points have to be shared because the triangles exist...

gray mural
steady moat
gray mural
steady moat
#

If there is no logic, and you only found it by trial and error.

#

You should use that directly instead of coming up with a math algorithm.

gray mural
#
if (currLine != 0 && currLine % (textLineCount * textIndex + 1) == 0) // change TextComponent
steady moat
jovial moon
steady moat
#

@gray mural

What is the relation between your number and the amended number ?

jovial moon
#

The numbers represent which vertices the UVs should have!

gray mural
#

or current line and current text index?

steady moat
#

current line and text index I would guess.

gray mural
steady moat
#

How does it depends on text index ?

gray mural
#

if textIndex is 10 and each textComponent contains 2 lines - currText is (10 + 1) * 2 - 2 = 20

#

it's the last line

steady moat
#

Why is that ?

gray mural
steady moat
gray mural
steady moat
#

I'm asking you the question.

#

You are not attempting to answer it.

gray mural
steady moat
#

You are just giving me observation.

#

I want to know what is the reason of those observation.

#

The reason of your observation will lead you to the formula.

gray mural
#

if there are just 2 textComponent - they contain e.g. 2 lines (it's changed via inspector). So the maximum lines they can contain is 4

#

2 * 2

#

but currLine and textIndex are indexes

#

so they start from 0

#

in order to get first line's currLine we need to do non-index from currText => += 1

#

then we multiply by textLineCount (2 in our case)

#

and then -= textLineCount

#

cuz index too

#

but I don't do it like this, cuz it's changed when new line is entered

steady moat
#

Why you need to that ?

#

You are showing me what are your observation.

#

I'm asking you what is the source of what you are seeing.

#

What text index represent ? And what text line represent ? What is the relation between them.

#

It could be like: The index represent the character and the line represent the amount of line require to show all character in a given space.

jade phoenix
#

is there a way to achieve something similar to the Update() function within a coroutine?

stable osprey
# jovial moon

oh.. now I got it :p then you definitely need a custom shader!
UVs are just a Dictionary<int, Vector2> equivalent, where key is vertexIndex and value is just some vector πŸ˜„

jade phoenix
#

while loop is causing it to crash

potent sleet
#

you need yield return null inside of it

stable osprey
jovial moon
stable osprey
#

performance-wise, yes πŸ˜„ but again, it could be TIME efficient, which may be worth it πŸ™‚

jovial moon
jovial moon
stable osprey
#

remember, you have 16ms worth of 'fuel' for your code to take up -- if you want 60fps

#

and the same amount on your GPU

jovial moon
#

Would the performance part come in in the setup, or the rendering?

stable osprey
#

1000 meshes + renderers may take 0.5ms, which is way below your 'budget' πŸ™‚

jovial moon
#

Ah, I see ^^

stable osprey
#

so, yup! unless you plan on rendering like 2million meshes, you could even go 1 mesh per triangle if it fits your need πŸ˜„

#

but doing it via single mesh & shader might be a fun way to spend your time too :p

jovial moon
#

And would submeshes be as efficient as Meshes?

jovial moon
#

I can't comprehend how the shader could identify which face it is on

stable osprey
#

submeshes are just some 'tech' to map different triangle sets to different materials -- ultimately on the same mesh

potent sleet
stable osprey
#

this is what the shader gets

#

and you have access to 2 functions: vert and frag

#

so, you could specify the UVs for the first triangle to be [0, 0.2], and of the 2nd triangle to be [0.2, 0.4]

jovial moon
#

Hmm I apologise, I am struggling grasping a few things still.

Imagine if my triangle always has the same order of vertices: 3 define the top, 3 define the bottom, in this order.
The top and bottom may be a different size and different angles on the triangles.
Would a shader be able to go "I am the back side", or "I am the top side"?

stable osprey
#

then in frag you could do:

int textureIndex = i.uv.x / 0.2;
float2 newUV = inverseLerp(i.uv % 0.2, 0, 1); // Remap it to [0,1] range
fixed4 color = tex2D(_AllTextures[textureIndex], newUV); // Get the correct texture
return color;
stable osprey
#

so if top part has UVs that go from 0 to 0.2, anywhere between those values would give away that the shader is rendering the top part

#

fragment shaders are a bit different than compute shaders, but only in that sense -- you have POS & UV to go with πŸ˜„

jovial moon
#

Could you please give an example of how the sides UVs could be set?

#

The 0 to 0.2 for the top part

#

(I understand separating it on the texture, if this is it?)

stable osprey
#
    Vector2[] UVs = new Vector2[12]
    {
        // Top vertices
        new Vector2(0   , 0) * 0.2f,
        new Vector2(0.5f, 1) * 0.2f,
        new Vector2(1   , 1) * 0.2f,
        new Vector2(0   , 0) * 0.2f,
        new Vector2(0.5f, 1) * 0.2f,
        new Vector2(1   , 1) * 0.2f,

        // Bot vertices
        new Vector2(0   , 0) * 0.2f + Vector2.one * 0.2f,
        new Vector2(0.5f, 1) * 0.2f + Vector2.one * 0.2f,
        new Vector2(1   , 1) * 0.2f + Vector2.one * 0.2f,
        new Vector2(0   , 0) * 0.2f + Vector2.one * 0.2f,
        new Vector2(0.5f, 1) * 0.2f + Vector2.one * 0.2f,
        new Vector2(1   , 1) * 0.2f + Vector2.one * 0.2f,

        // Side vertices
        new Vector2(0   , 0) * 0.2f + Vector2.one * 0.4f,
        new Vector2(0.5f, 1) * 0.2f + Vector2.one * 0.4f,
        new Vector2(1   , 1) * 0.2f + Vector2.one * 0.4f,
        new Vector2(0   , 0) * 0.2f + Vector2.one * 0.4f,
        new Vector2(0.5f, 1) * 0.2f + Vector2.one * 0.4f,
        new Vector2(1   , 1) * 0.2f + Vector2.one * 0.4f,
    };
#

probably not gonna compile like this xD but hopefully u get it :p

#

or.. well I messed up.. those are 6 vertices per 0.2 of UV

#
List<Vector2> UVs = new();
float offset = 1f / trianglesCount;
for (int i = 0; i < trianglesCount; i++) {
  UVs.Add(offset * (i * Vector2.one + new Vector2(0, 0));
  UVs.Add(offset * (i * Vector2.one + new Vector2(0.5f, 1));
  UVs.Add(offset * (i * Vector2.one + new Vector2(1, 1));
}

// aka
//for (int i = 0; i < trianglesCount; i++) {
//  UVs.Add((i * offset) * Vector2.one + offset * new Vector2(0, 0));
//  UVs.Add((i * offset) * Vector2.one + offset * new Vector2(0.5f, 1));
//  UVs.Add((i * offset) * Vector2.one + offset * new Vector2(1, 1));
//}
jovial moon
#

Okay so When it comes to textures - it's like this, right?

#

Of course T would be 0,0 to 0.5,1 to 1,0

#

Since it's a triangle

stable osprey
#

the idea with this would be that you could use a Texture2DArray to have a bunch of textures to choose from, one for each side (or something)

stable osprey
jovial moon
#

Yeah! So I get that part!

#

(And thank you for sticking with me for this long, by the way! ❀️)

#

But my issue comes with the UV definition

stable osprey
#

np actually took a superlong break meanwhile so I'm good πŸ˜„ and this is interesting

jovial moon
#

Glad to hear! 😊

#

So let's define the vertices
AT, BT, CT, AB, BB, CB

#

(A top, B top, C top, A bottom, B bottom, C bottom)

#

This is my biggest issue here with the UVs. Unless I can somehow tell the shader which side is which, it's an issue. Here is why!

#

Imagine the back face, AT, CT, AB, CB

#

Forms a full 256x256 texture, no issue so far!

#

Then the top forms a AT, BT, CT - still no issue!

#

CT, BT, CB, BB is what messes things up for me... Because the BT is shared

#

Maybe I just can't comprehend this properly and it's not that complicated, but I can't figure it out

stable osprey
#

wait what is T? πŸ˜„ I thought u just named the faces randomly. I don't see any such vertex

jovial moon
#

Oh! T stands for Top! A has a top and bottom variable because the original 2D triangle is extruded vertically

stable osprey
#

ah, ok got it. let me re-read now :p

jovial moon
#

Do you know if I can access the vertices of the current polygon the shader is figuring out the color of?

#

Their indices

#

Ah but that still leaves me very confused on the triangle part....

#

Also how do I define the UV of a single side anyway..? I mean, there are 6 vertices in this mesh...

stable osprey
jovial moon
#

But I only need 3 of them in the top..

jovial moon
#

I would ideally like to handle this with 5 submeshes in 1 mesh, but I got stuck on that approach :c

stable osprey
jovial moon
#

Sorry I'm not quite following this question!

#

I defined 2*3 triangles for the sides, and 2 for top and bottom

#

(Sides 2x because a rectangle requires 2 triangles)

stable osprey
#

6, right.. idk where 12 came from

#

I'm trying to think of a way to get the side via pos and uv instead of just uv

#

kind of something like: if (pos.y > -highest && pos.y < highest) { isOnSide = true; }

#

I'm sure it's possible but that overcomplicates the shader and it's not good either..

jovial moon
#

Yeaaaaaaah, there's another issue with that to begin with, unfortunately... I get my vertices from a generated platonic, so I don't really even know it's rotation all that very well...

#

I can center it, I can check the angle from the origin to the original position, but the... Clockwise? I guess? rotation would still be a mystery...

stable osprey
#

in the code you posted, highest is just topHeight -- and for the shader UV ranges and side/nonSide should be enough.. but oof, yeah I wouldn't wanna go there

jovial moon
#

Hmmm so I would really like to get my submeshes to have their own UV then!

#

What if though... What if I made copies...

#

Perhaps that would be fine, and it could even be in one mesh.

#

Not even submeshes

#

Is it a big waste to have multiple vertices in same positions?

#

Or would this be brute forcing a problem to begin with?

leaden ice
jovial moon
#

I see! Okay, thank you!!

leaden ice
#

(also normals, colors)

#

ALl of these mesh data are tied to vertices in Unity's mesh model

stable osprey
#

yeah I was considering using just a shader since it's very few triangles, but.. the complexity.. damn..

supple wagon
#

hey guys i have a question. i have a script with a public variable of the bool type, but i cannot access it from other scripts. could someone get on call and help me out? much appreciated

jagged snow
#

I'm looking for a guide on repeating parellax backgrounds for a topdown game, all I'm trying to do is have this background properly scroll based on the movement of the player. So far the guides are specific to auto scrolling backgrounds and 2d platformers i cant find any specific to what im looking for

leaden ice
#

Sometimes a guide doesn't exist for the specific thing you want to do and you have to think up how to do it yourself.

hasty silo
#

Hello, how would one go about programing in sound effects for only the player controlling the player? I was given some source code for a multiplayer game (first time in a multiplayer environment) and need some audio playing specifically to the player. Is there a way to do that?

steady moat
hasty silo
#

thats what I tried and I wasnt able to figure it out that way, mostly cause the comments were all corrupted for some reason and are in complete gibberish (i think they were in korean before I pulled everything) luckily i have a meeting with the head dev tmmrw so I will be able to ask him for directions. Ty for the input tho.

steady moat
compact spire
#

well, if your variables names are in a language you don't know, comments might help lol

steady moat
hasty silo
#

Very true, but its currently 1 AM here and i have a meeting in the morning with the dev at 9, I was hoping there was a straight forward way but if there isn't one and I need to rummage for a bit I think ill wait till I can ask the dev directly.

steady moat
#

Because of the special character.

#

I mean, there is probably a straight forward way. However, it would not be the "good" way.

warm stratus
#

Hey, i have sliders that active a function, but how do i do to make my sliders runs the function only if it s modified by hand and not by code?

steady moat
#

In the sense that you would duplicate concept.

compact spire
#

If I have a prefab with a reference to a scriptable object asset, and I instansiate that prefab, is the scriptable object it's own instance or is it just a reference to the asset (and thus changes to it will change the asset)?

warm stratus
compact spire
#

damn

leaden ice
compact spire
#

yeah I could, I'm still not sure it's the solution I want though

#

I'm still indecisive about using structs/scriptable objects/dictionary for my stats

#

scriptable object makes sense for base stats and all the modifiers, just doesn't make sense on the monobehavior itself since it won't be immutable. Creating an instance of the base stat SO and having it on the monobehavior isn't a terrible idea, but I won't be able to update them easily as they will be private set...

#

I could just put properties on the monobehavior and have a big constructor/method to apply all the SO stats to it, but that doesn't seem right

#

Maybe there isn't an elegant solution out there and I just have to comprimise.

steady moat
#

It should be in two part.

compact spire
#

Yeah that's one of the problems

#

I think I have a solution

#

I just have a common interface between a stats class and a stats scriptable object

steady moat
#

One part that is runtime. The other that is immutable that contains things like the name and the description of the stats.

compact spire
#

damn, I can't have the accessibility between the fields be different

dusk apex
#

Access modifiers are for regulating exposure of members and whatnot to other scopes.

compact spire
#

so if my PlayerStatsSO and PlayerStats class inherit from an interface that defines it's fields they require the same accessibility.

ashen yoke
compact spire
#

So GetInstance is just returning a clone.

ashen yoke
#

no it returns new Stats instance

#

its not a clone of SerializedStats

leaden ice
ashen yoke
#

SerializedStats is a simple pod, its values are used to initialize a complex Stats class

compact spire
#

Well, I appreciate all the input, I'll mull this over a bit more πŸ˜›

outer brook
#

I know you can reset a scene but is it possible to reset the entire game at once?

leaden ice
#

define "reset the game"?

#

you can't "reset" a scene either. You can load a new scene (perhaps the same one you were currently in), but there is no "reset scene" functionality

outer brook
leaden ice
outer brook
leaden ice
#

There's nothing to reset unless you are explicitly storing data somewhere

#

if you are

#

delete that data

leaden ice
outer brook
atomic plover
#

Hey, excuse me guys but I need some help with these errors in this code

leaden ice
#

additive scene loading?

#

Just do that again

leaden ice
#

You are referencing some types that don't exist

atomic plover
#

but how do I fix that

leaden ice
#

you need to define those types, or stop trying to use them

outer brook
leaden ice
#

Go back and learn the basics first

leaden ice
ashen yoke
dusk apex
#

Looks like a dirty port (copy/paste of code)

atomic plover
#

I basically copy pasted this controller script from a github repository

leaden ice
atomic plover
#

yeah it is

ashen yoke
#

you should copy the rest of the files

atomic plover
#

because im trying to finish a project

outer brook
leaden ice
#

scenes do not "get left as they are" when you reload them - that only happens if you are saving data somewhere external to the scene.

swift falcon
#

**If you have a parent GameObject with two child GameObjects and you want to perform specific actions on each child GameObject using separate functions, you can accomplish that by referencing the child GameObjects individually and calling the appropriate functions. Here's an example:

csharp
Copy code
public class ParentObject : MonoBehaviour
{
public GameObject childObject1;
public GameObject childObject2;

public void Function1()
{
    // Perform actions specific to childObject1
    // ...
}

public void Function2()
{
    // Perform actions specific to childObject2
    // ...
}

}
In this example, the ParentObject script contains two public GameObject variables (childObject1 and childObject2) representing the child GameObjects. The script also contains two functions (Function1 and Function2) that perform specific actions on each child GameObject.

To use this script, attach it to the parent GameObject in the Unity Editor. Then, assign the child GameObjects to the corresponding variables (childObject1 and childObject2) in the Inspector.

You can then call the specific functions to perform actions on the child GameObjects, for example:

csharp
Copy code
ParentObject parentObject = GetComponent<ParentObject>();

// Call Function1 on childObject1
parentObject.Function1();

// Call Function2 on childObject2
parentObject.Function2();
By accessing the ParentObject component attached to the parent GameObject, you can call the specific functions (Function1 and Function2) to perform the desired actions on the child GameObjects individually.

Note: Make sure the child GameObjects are assigned and active in the scene hierarchy for the functions to work correctly.**

-ChatGPT

Chat is this true?

steady moat
#

My eyes

swift falcon
#

sorry but I had to

leaden ice
swift falcon
#

Just asking to make sure it is not lying

leaden ice
#

this answer is also - basically meaningless

swift falcon
#

wut

leaden ice
#

it's just saying "by defining two different functions you can do two different things"

#

but... much more wordy

swift falcon
#

oh

#

sorry

leaden ice
#

you would be much better served here simply explaining what you want to accomplish and asking how to do it.

ashen yoke
#

delet

#

god also crossposted

swift falcon
#

yeah uhh... I have a script. It is attached to the parent gameobject. In the script I have two functions which are actioning two child gameobjects. How can I write in the code that thing? Like to access the two childs in the script attached to the parent.

#

and also, not just childs, can I do that with objects that are not even childs? like totally separate objects

steady moat
ashen yoke
#
transform.GetChild(index);
#

learn how to reference other objects

#

there are plenty of tutorials about it, literally n1 topic

steady moat
#

You should just take the time to follow tutorial.

leaden ice
steady moat
#

!learn

tawny elkBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

atomic plover
heady iris
#

such as, perhaps, !learn

tawny elkBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

scenic thicket
#

Hi, I have a problem with a property drawer, when I have a property like an array or a vector3 to show in the inspector, for example the vector 3 is drawn like default with x, y and z next to each other but then the same values x, y and z are drawn as seperate floats. How can I avoid accessing inside that properties.

#

Here is the code:

golden vessel
#

Hey, one of the object in my scene isn't at the same spot whether I'm in editor or in build. It's a prefab.
Anyone has an idea why that would happen?

dusk apex
#

It's not a prefab anymore if it's in the scene.
Folks will need more information to help you.

golden vessel
#

The buck isn't at the same position (top is editor, bottom is build)

scenic thicket
golden vessel
golden vessel
leaden ice
#

different screen resolutions and UI elements moving around

#

You have to anchor it properly

golden vessel
#

I guess I locked the aspect in editor and didn't check

#

Thanks for the info, I'll try working around that

#

Ho damn it's actually the rendered image from a camera that's causing the problem

compact spire
#

Since you are looking at child properties, maybe the 3 float values are considered children of Vector3?

simple egret
#

You might want to post that in #archived-resources instead, if you don't have any issues or questions about it

jade phoenix
#

is there a way i can link an object's rotation so that it's always the same as the camera's

jade phoenix
#

okey

#

how

simple egret
#

It'd be as simple as copying the rotation from one to another, if I understand it well
obj.transform.rotation = cam.transform.rotation;

jade phoenix
#

how do i grab the camera

#

do i gotta link it on the inspector or is there an easier way

simple egret
#

Inspector reference is by far the easiest and most performant, use that first if you can

quartz folio
#

Or you can just just a rotation constraint component

north swift
#

Anyone got any idea of how I could go about adding force (or setting velocity) to my character so that they wall jump in a curve? (This is done in Big Tower Tiny Square's wall jump)

EDIT: I've gotten it to work, basically just use an animation curve, and apply a constant force on the x axis, and use the animationCurve.Evaluate(_timeSinceYouStartedWallJump) as the y axis

dusky lake
#

Hey, uhh so I have a weird problem with unity events...

[Serializable]
public class ISpawnPacketEvent : UnityEvent<NetworkPacket<SpawnPacketData>> { }
[...]

    protected static ISpawnPacketEvent SpawnPacketEvent = new ISpawnPacketEvent();

    [...]

    public static void AddSpawnPacketListener(ISpawnPacketListener listener)
    {
        SpawnPacketEvent.AddListener(listener.OnSpawnPacket);
        Debug.Log(SpawnPacketEvent.GetPersistentEventCount() + " add");
    }

Console output:

0 add

How is this possible? I just added a listener to it

Sorry for the repost, figured this might not be right for the beginner section

timber snow
#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UI;
using UnityEngine;

namespace World
{
    public class ParallaxLayer : MonoBehaviour
    {
        public Vector2 ScrollFactor;
        public bool AutoAdjustPosition;
        private Vector3 Origin;

        private void Awake()
        {
            Origin = transform.localPosition;

            if (AutoAdjustPosition)
            {
                for(var i = 0; i < transform.childCount; i++)
                {
                    var child = transform.GetChild(i);
                    child.localPosition = new
                    (
                        child.localPosition.x - (child.localPosition.x * ScrollFactor.x),
                        child.localPosition.y - (child.localPosition.y * ScrollFactor.y),
                        child.localPosition.z
                    );
                }
            }
        }
        private void Update()
        {
            Vector2 offset = (Camera.main.transform.position - Room.CurrentRoom.transform.position);
            offset.x = (offset.x - 208) * ScrollFactor.x;
            offset.y = (offset.y - 120) * ScrollFactor.y;

            transform.localPosition = Origin + (Vector3)offset;
        }
    }
}

When a parallax layer scrolls, it jitters harshly with the camera. Is there any reason this could be occuring?

eager yacht
rugged goblet
#

And you won't see events added with AddListener in the editor, if you're expecting that

eager yacht
#

Can do a nasty hack to get the manually-added count, but I don't recommend it lol.

var mCalls = typeof(UnityEventBase)
    .GetField("m_Calls", BindingFlags.NonPublic | BindingFlags.Instance)
    .GetValue(myEvent);
var count = mCalls.GetType()
    .GetProperty("Count", BindingFlags.Public | BindingFlags.Instance)
    .GetValue(mCalls);
jade phoenix
#
    public Transform player;
    public float cameraSpeed;

    // Update is called once per frame
    void Update()
    {
        transform.eulerAngles += new Vector3(-Input.GetAxis("Mouse Y") * cameraSpeed, 0, 0);

        player.transform.eulerAngles += new Vector3(0, Input.GetAxis("Mouse X") * cameraSpeed, 0);
    }``` Hey so I have this script which is attatched to the camera, and it's supposed to rotate the player object horizontally when the mouse moves, but when I try using the Vector3.forward in the player class, it only ever points one direction.
timber snow
#

vector3.forward will always be (0, 0, 1)

#

transform.forward will be the local z forward vector

jade phoenix
#

ah okay

#

how do i do this for other params like left, right, back, etc.

#

just rotate the forward vector?

#

oh it looks like it has a right but not a left

#

weird

zenith parrot
#

Hello is this the right channel for questions about NGO (sorry if not I'm new here)

prime mica
#

Sorry if this is documented somewhere, but is it intended functionality that scripts in inspector have an actual execution order? i.e script A being above script B in inspector means script A runs first?

zenith parrot
#

thanks !

prime mica
#

so in this picture, does attachment run, then once it's called it's Awake() OnEnable() Start() etc does WeaponComponent then do the same, or does it not matter what order they are in?

#

because I had an issue that was fixed by swapping their positions

#

and I'm not sure if it's my code, the intended behavior of scripts in inspector or both

rugged goblet
#

You can expect components to be called in the order they're in under normal circumstances

#

But you can edit script execution order in preferences

lean sail
jade phoenix
#

do i need to Abs() Vector3.Distance()

#

or does it do it for me already