#archived-code-general
1 messages Β· Page 147 of 1
How is the vehicle moving?
as in, what mechanism is being used
a rigidbody? just setting the transform's position?
does the rigidbody have interpolation enabled?
No
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.
Have to smooth out the camera motion
that's a separate matter
if interpolation was enabled, the object would appear to move every update
not every physics update
it should
it basically smears out the movement of the rigidbody over the frames between physics updates
So, do I enable interpolate?
Start by moving that code to LateUpdate and seeing how it looks
The camera code? The camera goes wild
if you camera was still updating in FixedUpdate, you would then see jittering, since the vehicle would move every frame, but the camera would only move 50 times per second
well, you need to switch to Time.deltaTime, at the least.
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...
This same method but in LateUpdate, finally the camera is not left behind, it is always in the same spot relative to the vehicle
so yeah, it was an order-of-operations issue
FixedUpdate runs before the physics system updates
But wait
go with the latter. use ScriptableObjects just as data containers and you'll have a better time. especially since SOs have a bit different behaviour in the editor than they do in a build
using smoothtime
well, this sounds non-wild
you will have to explain.
kk
i am not psychic and i cannot see your screen
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
your smoothsdamp is still instant, isit not?
no
I gave it 0.1f
with higher damping value the jitter is less notisable
but it happens with lerp as well
@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)?
i'd like to suggest using cinemachine for your camera controls as you'll get better behavior from it than what you are getting with the code you are writing
It's very hard to say anything with that janky framerate
I'd expect this to happen with a very high framerate
wrap it all up in a struct or class then use = one time!
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.
there is not
The game is running at 60FPS but the PC is not powerful enoight to record them
since it would smear out the rigidbody's movement
When I tested Cinemachine I didn't have the Jitter problem
right, that's kind of the idea of using cinemachine. you won't experience the problem you are getting from your own code
@leaden ice Oh, so just have them share the same struct/class?
We've been suggesting Cinemachine to him for like 4hrs now lol
Or I guess that would be a model
Yes I know sorry
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
you'd still need to create the instance of the class from your SO which means it will end up with the same issue of needing to assign all of its properties
these sharp regions are the borders of the voronoi biome map
why i cant press button in world space UI?
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 π
can you press buttons in screen space UI in the same scene?
( biomes also have a height cutoff and clamps some biomes to specific heights btw )
Ok, got it, let me dive into it then
but I imagine something to smooth out the heights would have to ignore the heightcutoff of each biome

@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?
i mean at that point, why even use the scriptable object? why not just serialize the data class/struct directly on the monobehaviour?
indeed. especially if you aren't going to be "re-using" the data much
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];
i.e. you aren't going to attach that data to many different things
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 π
@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.
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.
"in a way that makes sense"
you mean like a serialized field directly on the MonoBehaviour which is likely what you were going to do for the SO anyway? but instead of filling out the data on a serialized field on the SO just to drag the SO to the MB you would instead just fill out the data on a serialized field directly on the MB
mark a struct or class as serializable and it shows up in the inspector.
i already have EventSystem
congrats. if you are still having trouble with it, then ask in the relevant channel like i said
ok
at this point, what benefit is there to using the SO?
testing changes at runtime?
you sure you're cahging the values in the instances and not the prefabs?
why wouldn't you be able to do the same thing with a serialized field?
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
sure but their idea was to apply the data from the SO and then no longer be using the SO data anyway
The thing is, I am instantiating a gameobject from a prefab, that prefab is SerpentFeng which has Sword as a subclass, so basically I call Use() of the Sword class but it should still be the subclass of the instatiated gameobject right?
Only if... you're actually calling it on the instance and not on the prefab
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
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.
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 π€¦
Weapon.Use() would be a compile error
unless you have a variable somewhere like Weapon Weapon;
I do yea
public Weapon Weapon { get { return _weapon; } set => OnAcquireWeapon(value); }
public GameObject WeaponObject { get { return _weapon.gameObject; } set { _weaponObject = value; } }```

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
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
that property is super busted
yeah so - exactly what I was saying above - you were calling it on the prefab and not the instance
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
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
the GameObject reference doesn't help you with that at all
you can just as easily do .transform from any component reference as you can from the GameObject reference
Yep! Again thanks for the help now and before! Will fix the bugs and hopefully get it working now!
Thank you every one for your support guys
Cinemachine turned to be best option
to avoid headaches
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...
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
Well, yeah, you're just calling the other implicit cast. There's no conversation happening here.
do i have to use "explicit operator" then
yeah, you need an explicit conversion in there to break it up.
You don't need an explicit operator, you just have to actually convert it instead of just returning the object, which will invoke the implicit operator again.
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?
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.
What do you consider to be a lot? They are not instanced draws at least.
couple thousand
Yes they are pretty slow
I find my package to be faster https://github.com/vertxxyz/Vertx.Debugging but depends what you're drawing, I use both
oooo this looks useful thanks!
(text in my package is really slow as it's just IMGUI, but it doesn't exist in default sooooo)
Why would you need that many gizmos active at any given time?
For me, I am using Entities and my authoring scene is mostly gizmos, only at runtime does my game spawn graphics
are you optimising a networked server or are you trying to optimise editor ?
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?
well first you'll want to set up drag on the rigidbody
Ah, so rather than programming counter movement you could just use drag.
alright.
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
Also? So I add counter force and drag? How could I go about adding counter force. I am having an issue where the player isn't moving in the direction the camera is facing. This is my script currently: https://hastebin.com/share/gatofezoca.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
I have the player rotating with the camera
transform.rotation = Quaternion.Euler(0, Camera.main.transform.eulerAngles.y, 0);
then your movement should be correct with the direction the camera is facing. provided your player is actually rotating with the correct camera
oh my god, I deleted the original main cam and made a new one, and forgot to give it the MainCamera tag
you should have been getting a NullReferenceException. don't ignore the errors in your console
Alright, I have encountered another issue, i think adding drag caused me to be unable to jump.
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
Is this better? groundCheck = transform.Find("GroundCheck").GetComponent<GroundCheck>(); in start() and return groundCheck.isGrounded; in IsGrounded()
yes that is better
Alright, thats good.
thank you
Uh, this seems wrong. https://streamable.com/t0663b
what's wrong?
I press the jump key, and i flew out of the atmosphere
have you considered using less force? the reason this is happening is because you are probably using a lot of force from when you were compensating from not using the right forcemode
and also you seem to be adding vertical force every frame equal to the current velocity
Im only using a float value of 2
show the inspector
the whole line 24 of your script is very dubious :p
can you show what the code currently looks like?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you're still adding the rigidbody's Y velocity in your AddRelativeForce call
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.
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
wait, i figured it out, its a lag spike
How can i go about applying counter movement?
forces in the opposite direction
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
if it's a !bug with the editor that you can consistently reproduce then you'll want to report it π
πͺ² 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
also this is a code channel
like this? counter = speed/2; in Start() and rb.AddRelativeForce(-movement.x * counter, 0, -movement.y * counter); in Update()
Yes sorry, I've just sent it because I couldn't find other related channel...
but thanks! I'll ask there!
wait no, it cant be that, because i just tried it and it didnt work
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.
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;
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)
and lerping between 0 and 1 is just the value (clamped to 0-1) and lerping between 1 and 1 is just 1
I'm just doing this on a graph ab
I think the lerp is equivalent to just (1 - value) * value + value
when value is between 0 and 1
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
Calling a non-static method without creating a copy
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 ??
Assigning Renderer.materials copies
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.
Because it copies individual element
If the renderer has two materials they're separate instances and therefore have unique IDs, even if they're the same material
There is Renderer.sharedMaterials but you'd need to manage it well
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 ?
Nice XY problem
Where does the two element requirement come from?
So there is no way to not duplicate the material? No way to keep the original material?
via code? Just assign βrenderer.material = some material;β and it'll be duplicated
or to be more explicit renderer.material = new Material(someMaterial);
I don't want to duplicate it, that's my problem
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?
this is possible via renderer.sharedMaterial = or renderer.sharedMaterials =
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
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 ?
Or am I mistaken?
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
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
ValueChanged?.Invoke();
So Events are objects? Also thank you!
its a delegate
kinda π
its an object yes
Ahh I need to google what delagates are before asking dumb questions haha
delegate is just an array of method pointers, essentially, wrapped in very heavy syntax sugar
Hmm
yes pls
Shows a simple C# delegate declaration and how the compiler converts delegates to normal class type.
Jamie King, the man the myth the legend π π π
Okay so a delagate is basically just like a shorthand of a class with syntax sugar
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
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.
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 :/
show code?
- I can answer but can't read your question π
Can I send code here ? it's about 50 lines, may be a bit clogging for the chat
hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
cool! need 3'
Thx!
does load or doesn't?
It does
well that's what should happen, no?
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
so it says.. Loading previous scene: (empty as null), and then it loads some scene?
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
also, you should make sceneBeforePlay = ""; after loading to have it be safer
No it doesn't, it failt the condition. I checked the value of sceneBeforePlay right before the "if" just to be sure
Uh. I found a solution that is working
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
}
it works but I don't understand why at all lmao
i'll try
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
there is built in way to override play scene
also make sure to make it toggleable so it won't become a hinder sooner or later
It worked too !
EditorSceneManager.playModeStartScene
A hinder, what to you mean ?
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
Oh damn. Does it set you back to the scene you where on before hitting play button ?
maybe in project settings or a keybinding
i think yes
because i dont see any code that stores opened scene anywhere
only setting it to null on ExitPlaymode
Aaah yeah I see. It's unlikely to be a probleme I feel like. Though in the constructor I did put a log to say force loading to scene "xxx" was enabled. so it doesn't fall into oblivion xD
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
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
yeah but that would imply having it on all scenes, while it's just a unity editor script I want
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
How do you set it to a scene ? I am new on unity, I don't get how you set it to a specific scene ?
I wouldn't be able to argue if it's the best, but considering the use I have for it right now, it seems to be the best
get the scene asset
AssetDatabase.LoadAssetAtPath<SceneAsset>(assetPath)
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
why so?
Yeah, why ? :o
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
also you shouldn't need full class for this. You can have a class with editor functionality and just add this:
[InitializeOnLoadMethod] static void SetStartingScene() => EditorSceneManager.playModeStartScene = AssetDatabase.LoadAssetAtPath<SceneAsset>("Assets/Scenes/InitLoading.unity");
playModeStartScene is a property, not a method
right, fixed
Sorry but I didn't get the issue ? Just tested with all my huge amount of 3 scenes, and it worked like a charm.
It feels naked without a class around, but yeah you are right lmao. I may need more customization to make my developmment more comfortable later on I guess. I am just getting started on Unity
create editor window class, shove in it all functionality you need, keep it open
my favourite editor thingy is my in-game shortcut disabler: https://gdl.space/kukezowico.cs π
I can press ctrl+Z/ctrl+S in editor and not hear BEEP sounds
That's many concept I never heard of yet
technically could restore to Default instead of custom Editor Default (... I think)
yeah that'd be a nice workaround for toggleable boolean π
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
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 =
I renamed them to the correct ones now, thank you!
So I'd have 12 indices in the UV total - vertex count * submesh count?
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
Have you referenced this asmdef from yours?
hm well you said you want different textures, right? do you get 2 materials for the mesh you create? or one only?
Hrm, looks fine. I usually override references and reference plugins manually to have more control
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 (?)
2 materials! Although I don't really mind, I can have 1 and set the UVs accordingly
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
if it's a DLL, you'll need to 'override references' on the asmdefs that need it, and manually select it from the dropdown
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...
yeah haha this is mesh packing work.. it's the first time I see someone using submeshes and not pack UVs actually
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.
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)
So this would put all 3 textures into one, for UV use?
@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
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?
are you familiar with shaders?
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!
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
I see so I will need a shader most likely, that works! Thank you!
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.
I'm a little confused.. This intends to make some vertices share the same UVs?
Vector2[] UVs = 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)
};
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);
each vertex should be getting the UV to use from its index in vertices array
so vertices[5] should be using uvs[5]
so yeah realized I might not be the best one to help with submeshes π
what do ppl here feel about usage of Invoke and InvokeRepeating?
I've read few forum posts with very polarized views
Who cares
They have their niche use
The only downside they have is fixable with nameof()
I was wondering why we couldn't just pass it as Action rather than string
like how coroutines do it
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
oh I didn't knew that
yeah I guess
would be cool if they updated it
That's why you do it like StartCoroutine(Foo()) and not StartCoroutine(Foo)
The latter would be an action, or actually delegate
Nah, StartCoroutine accepts an IEnumerator, which is what your Coroutine function returns
You get the idea
yeah
You can probably make your own Invoke extension though
I wonder if any unity devs can explain why invoke is (still) reflection based tho
I was thinking that
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
To cancel the Coroutine?
I'll do you one better
oh?
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();
}
}
You usually only use cancellation tokens with asynchronous methods, but the idea is cancelling delayed processes, which fits under this
Its your method
Sure, you can pass anything
reading code in discord is painful 
ngl thats p good
Format your !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.
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
Enumerators are nice when you get the hang of it
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
agreed
You can also make custom stuff if you know how, and recursion is way easier
recursion itself is sometimes like shooting yourself on the foot
I had far too many bad memories using it
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
Yes, I'm used to doing it
Js dev?
My code configuration forces it, and I am indeed a typescript developer
I fixed the code to no longer overflow and the syntax should be valid now
So this can literally go on forever, no matter what
its all psudo code anyway
ngl personally I would move it from update to fixedupdate and add fixeddeltatime
since floats and doubles are not 100% precise
coroutines 2.0

I would only use FixedUpdate for physics calculations since that is the whole point of it
That's not going to make it any more precise π
Might even make it worse
I don't think so
I'm not checking a precise number so it would not matter
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
since deltatime will be different every update
there is probably more room for error
also need to carry over the remainder
Yes, that's the point
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);
}
}
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
I mean yeah
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
there is time to execute and every electronic device has imperfections
never use delta time for accumulation
there is next tick pattern which is better in every way
isn't deltaTime time between current and last frame anyway?
oh?
The interval in seconds from the last frame to the current one (Read Only).
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
eh?
its incorrect
Do you have a source for that?
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.
trust me bro
yeah I'll need a source too tbf
could you be talking about smoothDeltaTime or something?
yeah I feel like thats what they're talking about
it seems to smooth out the difference over time
rather than do it instantly
Why would it be better if Time.DeltaTime is the exact time between each Update? π€
What you're doing is basically determing what Time.DeltaTime is, and storing that seperately
because there wont be float math error accumulation every frame happening
if you run 2 timers for a very long time, the one that accumulates delta will be off
That's true, you do have the drawback of that
A very long time
the tick with carrying reminder over also suffers from that but the error accumulation is much slower
depends on your game
i encountered this when i was making a train sim with time acceleration
I mean they claimed it can go on forever so 
#archived-code-general message
classic x4 x16 speed
I think forever is a very long time
You can see above, on frame 8, that
unscaledDeltaTime(d) anddeltaTime(e) differ in how much time they report has elapsed. Although a whole second of real time elapsed between frames 7 and 8,deltaTimereports only 0.333 seconds. This is becausedeltaTimeis clamped to themaximumDeltaTimevalue.
I didn't know this. This would makeTime.deltaTimenot suitable for accurate time keeping, unless you increasemaximumDeltaTime
just use decimal 
I guess. You should not count time any way.
Use a start time instead.
You may need to in some cases, such as if your timer needs to pause or have a different time scale than Unity's.
i was wrong, it is the time between start of the previous frame and start of currently processed one
yeah basically what we were saying
I'm glad you've fact checked it though 
mistakes happens to best of us
Note my interval variant does not actually make use of Time.Time, so it does not have the problem where it will become inaccurate when running for a long time. With running forever I mean that there is nothing that actually stops the method, due to the fact that the method is recursive, and nothing can overflow. So this does in fact never end if you let it run forever.
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 π)
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?
theoretically visual scripting can do anything C# can - but it would probably easier just to write it in C#
Time.time also suffers from the maximumDeltaTime problem, so frames that take longer than 0.333 seconds will be clamped, unless you increase maximumDeltaTime from its default.
I prefer Visual Scripting. I have a designer background and really like it this way.
They're both still better than Coroutines π
have you considered using another filetype like CSV?
if you can read files with visualscripting
CSV's layout would be way easier to work with
than JSON
netwonsoft.json 
how do I feed it trough the parser?
it's in the code examples you're looking at
ToJson would make it to a json type
(you'd also have to have defined such an object)
yeah you're looking for from
I honestly love using newtonsoft's json linq library for json stuff
IDK Visual Scripting is adding such an unecessary layer of complication here
makes it feel more like JS way of doing it
ikr this would be a one liner
I think it would be easier to learn C# than to get JsonUtility.FromJson working in Visual Scripting
C# and JSON work weirdly
mostly because a C# class/struct needs to be defined to receive the data
it's a questionalble statement
huh ? JSON is just a special text file. C# handles text files just fine
tbf at that point anything is a special text file
yes indeed
no like I want to know why
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
i know I am already in that discord. but that discord is quite death
Type is the object you have to make it
response time is a day or so
not a lot of people use visual scripting as much
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.
not really a code question...
what should be the Type be?
You can hide assets from packages by clicking the eye icon in the top right corner.
a class or struct you defined that matches the JSON object layout
you can also use this
https://json2csharp.com/
you need to tell the parser how your json object is "structured"
They don't belong to a package though. They are generated in my project as part of specific VFX Graphs I've made. But they are useless on anything other than the graph they belong to.
For example, this explosion I made creates many of these materials. But I would never want to use them on anything other than this graph.
I don't know then. Sounds like an oversight on Unity's part.
I tought I make it easy to adjust the quiz question by just editing a text file.
but I guess I have to do it like this?
also your json is prob wrong,
you need to make the answers strings
The two are not mutually exclusive
eg
public class Questions
{
public int question { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
}
no clue how would you use it inside of visual scripting tho
you need a "template" to modify your json file
or read it
JsonUtility isn't gooing to work with properties
also probably better to just use an array for the answers rather than numbered variables
very true, i just copied their json into the converter :p
yeah that's probably better to use with visual scripting
newtonsoft is amazing
because defining a class is ??? in VS
this is basicly the idea I had. that is the INT = 1 then that is the correct answer.
and somehow substract this data from a text file
no i know
this is just simply explained
{
"Question": "What is unity",
"Answers": [ "Game Engine", "Tea Party", "Shopping Mall" ],
"CorrectAnswer": 0
}``` this would be one way to do it in JSON
thanks and 0 becouse it is the first one in the list?
yes
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
using JObject as mentioned above would be an easyish way
is this a plugin/asset/package? or is this a node I can use in VS?
its a c# library
if it reflects yes
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
you understand what the error says?
Not really? I dont know what System.Memory is and i dont know why this came out of nowhere
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
InputSystem 1.4.4 is pretty out of date. Have you tried updating it?
update all packages and delete library folder
Ill try that.
Je moet ook geen Visual Scripting gebruiken π
haha vind het fijn werken
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
unfortunately didn't fix it
yeah, weirdly now it says 1.6.1 instead of 1.4.4
so the version isnt the issue im sure
this happened when i reloaded a solution
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'
Try to change your .NET Profile https://docs.unity3d.com/Manual/dotnetProfileSupport.html
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
What is the logic behind those numbers ?
// that doesn't work
currLine += (value - textIndex) * textLineCount - 1;
Because you can do something with just those numbers, but it will not have a logic.
is there like a general help?
currLine represents current line in the text, textIndex represents current TMP_Text
i need help with using the ml agents package
thanks
value - textIndex is difference between new textIndex and old one (it's setter)
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
Nooooo, I was just confused....
I want my top UV to have the first 3, and the bottom one the last 3
This did work!
now that i have a button, how to configure it so when i press it a new interactable panel should spawn
But then the issue was adding the sides
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...
I'll draw something!
Why you need to do so ?
cuz I need to count lines in custom input field when changing TMP_Text
So, you do not know what is the cause of the variation beween the number ?
What do you mean? Are you asking when do I change TMP_Text?
Why do you need to amend the number ? Where does the difference between those number comes.
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.
I need to control current line to know when to change textComponent
if (currLine != 0 && currLine % (textLineCount * textIndex + 1) == 0) // change TextComponent
Why, do you need to change the number ? Why the number does not work as is ?
@gray mural
What is the relation between your number and the amended number ?
The numbers represent which vertices the UVs should have!
What numbers you mean? textIndex and value?
or current line and current text index?
current line and text index I would guess.
current line depends on text index
How does it depends on text index ?
if textIndex is 10 and each textComponent contains 2 lines - currText is (10 + 1) * 2 - 2 = 20
it's the last line
Why is that ?
because I need to calculate current line based on lines in each text Component
Why is that when textIndex is 10 then each textComponent contains 2 lines - currText is (10 + 1) * 2 - 2 = 20
hold on, I will record a video for you to better understand the logic.
right, I am trying to answer it
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.
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
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.
is there a way to achieve something similar to the Update() function within a coroutine?
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 π
while loop
while loop is causing it to crash
you need yield return null inside of it
on the shader you could have something like a Texture2DArray where you add multiple textures, and change between them based on UV
Oh! And if I made 5 Meshes, one for each face - would that be incredibly inefficient?
performance-wise, yes π but again, it could be TIME efficient, which may be worth it π
Hmmm how could I know in the shader where I am?
Performance matters a lot to me so that won't be an option, I see! ^^
remember, you have 16ms worth of 'fuel' for your code to take up -- if you want 60fps
and the same amount on your GPU
Would the performance part come in in the setup, or the rendering?
1000 meshes + renderers may take 0.5ms, which is way below your 'budget' π
Ah, I see ^^
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
And would submeshes be as efficient as Meshes?
Yeah..! I am just worried how to know where I am in the shader
I can't comprehend how the shader could identify which face it is on
submeshes are just some 'tech' to map different triangle sets to different materials -- ultimately on the same mesh
public float CoroutineFloat = 10000;
public float UpdateFloat = 10000;
IEnumerator Start()
{
while (true)
{
CoroutineFloat -= Time.deltaTime;
yield return null;
}
}
private void Update()
{
UpdateFloat -= Time.deltaTime;
}```
Same thing
hmm so I showed you this:
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]
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"?
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;
yes, you would be able to determine which side you are on by reading the UVs that are sent to the shader
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 π
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?)
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));
//}
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
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)
yes!
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
np actually took a superlong break meanwhile so I'm good π and this is interesting
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
wait what is T? π I thought u just named the faces randomly. I don't see any such vertex
Oh! T stands for Top! A has a top and bottom variable because the original 2D triangle is extruded vertically
ah, ok got it. let me re-read now :p
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...
ah, I see now.. well you might have to duplicate the vertices instead of sharing them
But I only need 3 of them in the top..
Yeah! This seems to be coming back to a 5 mesh solution again..!
I would ideally like to handle this with 5 submeshes in 1 mesh, but I got stuck on that approach :c
hm.... so from this you defined 12 additional triangles to make the 3 faces? (one for each side)
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)
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..
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...
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
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?
you need that if you want separate UVs
I see! Okay, thank you!!
(also normals, colors)
ALl of these mesh data are tied to vertices in Unity's mesh model
yeah I was considering using just a shader since it's very few triangles, but.. the complexity.. damn..
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
Do not Crosspost
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
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.
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?
It depends on the code you have in your possession and the sound you want to play. You should study how it has been done in other part of the game.
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.
Comments are not necessary to understand codes...
well, if your variables names are in a language you don't know, comments might help lol
Kinda hard to use an other language than english in code.
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.
Because of the special character.
I mean, there is probably a straight forward way. However, it would not be the "good" way.
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?
In the sense that you would duplicate concept.
perfect, thks
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)?
i think it s a reference to the asset
damn
It is a reference.
you could manually create a copy if you want:
void Awake() {
mySOReference = Instantiate(mySOReference);
}```
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.
The stats itself should not be a scriptable object. The SO should be immutable. Otherwise you might find yourself with issue such as memory leak or the thing that you experienced.
It should be in two part.
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
One part that is runtime. The other that is immutable that contains things like the name and the description of the stats.
damn, I can't have the accessibility between the fields be different
Access modifiers are for regulating exposure of members and whatnot to other scopes.
so if my PlayerStatsSO and PlayerStats class inherit from an interface that defines it's fields they require the same accessibility.
class StatsData : Scriptable
class SerializedStats
{
public float health;
public float strenght;
...
public Stats GetInstance()
{
Stats stats = new Stats();
stats.Add(new Stat(Stats.Health, health);
...
return stats;
}
}
So GetInstance is just returning a clone.
yes SOs are most conducive to use as immutable data stores
SerializedStats is a simple pod, its values are used to initialize a complex Stats class
Well, I appreciate all the input, I'll mull this over a bit more π
I know you can reset a scene but is it possible to reset the entire game at once?
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
like the entire thing
that doesn't mean anything
resetting multiple scenes at once
There's nothing to reset unless you are explicitly storing data somewhere
if you are
delete that data
Again, resetting a scene is not a thing in Unity. If you want to load a scene, go ahead and load it with SceneManager.LoadScene
can you do a similar thing but with multiple scenes?
Hey, excuse me guys but I need some help with these errors in this code
how did you get multiple scenes in the first place
additive scene loading?
Just do that again
read the errors
You are referencing some types that don't exist
but how do I fix that
you need to define those types, or stop trying to use them
no I created them
You seem to be trying to write some intermediate level code without understanding the basics of C#. This is a mistake
Go back and learn the basics first
btw this didn't make your request any less vague. It made it more vague. Explain clearly what you're trying to do
where did you get this class?
Looks like a dirty port (copy/paste of code)
I basically copy pasted this controller script from a github repository
if you copied this script from somewhere you need to also copy all of the other scripts from that source
yeah it is
you should copy the rest of the files
you need the rest
because im trying to finish a project
I am making a game and I wanted to have the game replayable without having the player close it and re-open to do so as the scenes end up being left as they are if you attempt at replaying without closing it so I wondered if once you get a game over or you beaten it before taken to a main menu the entire thing in the Player's POV is reset
just reload the main menu or first scene or whatever
and again - #archived-code-general message
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.
**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?
My eyes
sorry but I had to
can you not dump a bunch of ChatGPT stuff in here lol
Just asking to make sure it is not lying
this answer is also - basically meaningless
wut
it's just saying "by defining two different functions you can do two different things"
but... much more wordy
you would be much better served here simply explaining what you want to accomplish and asking how to do it.
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
You want to reference the object with something like GetComponent or [SerializeField]
transform.GetChild(index);
learn how to reference other objects
there are plenty of tutorials about it, literally n1 topic
You should just take the time to follow tutorial.
public GameObject someObject;``` drag and drop the desired object into the field in the inspector and now you can do whatever you want with it
!learn
π§βπ« 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/
can anyone give a link or just the name of a place where I can re-learn the basics of C# unity, the course I used didn't register with me, (might be my fault).
such as, perhaps, !learn
π§βπ« 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/
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:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
It's not a prefab anymore if it's in the scene.
Folks will need more information to help you.
I'm not sure what info to give =x
The buck isn't at the same position (top is editor, bottom is build)
maybe check if the transform of the prefab is the same when in the project folder and when in the scene
The best guess I have is that I move the parent's position at the start of fight, and that this doesn't work in build
is it a UI element?
The parent is
well that's why
different screen resolutions and UI elements moving around
You have to anchor it properly
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
Help
Since you are looking at child properties, maybe the 3 float values are considered children of Vector3?
You might want to post that in #archived-resources instead, if you don't have any issues or questions about it
is there a way i can link an object's rotation so that it's always the same as the camera's
Yes
It'd be as simple as copying the rotation from one to another, if I understand it well
obj.transform.rotation = cam.transform.rotation;
how do i grab the camera
do i gotta link it on the inspector or is there an easier way
Inspector reference is by far the easiest and most performant, use that first if you can
Or you can just just a rotation constraint component
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
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
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?
Persistent events are the events that are assigned in the inspector.
And you won't see events added with AddListener in the editor, if you're expecting that
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);
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.
vector3.forward will always be (0, 0, 1)
transform.forward will be the local z forward vector
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
Hello is this the right channel for questions about NGO (sorry if not I'm new here)
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?
#archived-networking and the discords pinned in there
thanks !
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
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
the order shouldnt matter, you should fix the race condition regardless
assuming all objects exist prior to a frame, they will all run their Awake() then all run their OnEnable(), then all run their Start()
Hmm i see, thanks
