#archived-code-advanced
1 messages ยท Page 177 of 1
gotcha
But the GC Unity uses doesn't actually move anything, since it's a non-compacting GC
Hence why it's not a problem there, for now
That's actually part of why Unity is taking so long to move to CoreCLR
The engine assumes a non-moving GC all over the place internally
What about UnsafeUtility.PinGCObjectAndGetAddress? or is that something different?
That is safer yes
clarify about different values, what format is the graph in?
Safer at a slight performance cost
You also need to call ReleaseGCObject after you've set the value after
One node can return text + a bunch of options. Another can return images and audio
both have the same base class
i mean, you said you are parsing, is it some json?
var offset = UnsafeUtility.GetFieldOffset(field);
var address = (byte*)UnsafeUtility.PinGCObjectAndGetAddress(obj, out ulong handle);
ref int field = ref *(int*)(address + offset);
// set the field here
UnsafeUtility.ReleaseGCObject(handle);
what are you parsing it from/to?
@urban warren do you need to have the fields you're controlling be raw values?
can you do a wrapper class
that would allow you to manage stuff behind the scenes without having to deal with reflection
and you can use generics to make accessing less obnoxious
Wrapper classes around what?
you're doing the windcontroller thing right
yeah
just scriptable objects
anything that wants the data
So can you make the wind speed reciever field a class
That has a getvalue function or something
It's all general. The field could be from any component/asset
I'm confused
Oh wait, I think I get it
You want to create a unity event style popup (for example) that allows you to select and sync a value from another class
Yeah in broad terms
So your issue isn't the reciever it's the field you're getting values from
I thought this was a more structured thing
if you want to serialize objects you can use some library like Json.Net, it handles graphs fine by itself, and result is a json string.
You can extend it with custom converters to handle unity types like textures etc
then you would convert a texture reference to its project guid
and vice versa
I thought your issue was setting it bc you were talking about setting values
Ah, yeah my bad. It is both read and write
Mine
if I were trying to do this I would probably approach it like each shared value is a scriptableobject-like thing
doesn't have to be, but it's the closest example
here's some fun
static class ReflectionUtility
{
static readonly uint s_ObjectHeaderSize = GetObjectHeaderSize();
public static ref TField GetValueRef<TType, TField>(ref TType value, FieldInfo field)
where TType : struct
{
Debug.Assert(typeof(TType) == field.DeclaringType);
Debug.Assert(field.FieldType.IsAssignableFrom(typeof(TField)));
var offset = (uint)UnsafeUtility.GetFieldOffset(field);
return ref Unsafe.AddByteOffset(ref Unsafe.As<TType, TField>(ref value), offset);
}
public static ref TField GetValueRef<TField>(object obj, FieldInfo field)
{
Debug.Assert(field.FieldType.IsAssignableFrom(typeof(TField)));
Debug.Assert(field.DeclaringType.IsAssignableFrom(obj.GetType()));
var offset = (uint)UnsafeUtility.GetFieldOffset(field);
if (!obj.GetType().IsValueType)
offset -= s_ObjectHeaderSize;
return ref Unsafe.AddByteOffset(ref Unsafe.As<StrongBox<TField>>(obj).Value, offset);
}
static unsafe uint GetObjectHeaderSize()
{
var box = new StrongBox<byte>();
fixed (byte* pValue = &box.Value)
{
ref byte a = ref *(byte*)Unsafe.As<StrongBox<byte>, nuint>(ref box);
ref byte b = ref *pValue;
return (uint)Unsafe.ByteOffset(ref a, ref b);
}
}
}
that is fun
@urban warren so in other words, you have some kind of central data store for all your shared values and it handles getting and setting centrally
so what you get in your local component is a wrapper class that talks to that db
no reflection necessary, and no weird writing of unsafe values
plus the intent is a lot clearer
in the code, that is
I don't think I understand. How would that work?
Would I need to create a wrapper class for each field/set of fields?
I think I am doing something wrong... It is about 3.5 times slower than reflection when I tested it
super sketch framework:
class SharedDatabase {
public static Dictionary<guid,SharedValue> values;
}
class SharedValue {
public object value; // or spell it out a la serializedobject
public T GetValue<T> () {
return value as T;
}
}
class SharedValueWrapper<T> {
guid mySharedId;
public T GetValue () {
return SharedDatabase.values[ mySharedId ].GetValue<T>();
}
}```
Since it creates a GCHandle
and the same idea for setvalue
your editor code would manage the creation and syncing of guids and such
SharedValueWrapper is what would be serialized in your component
since unity supports generics now you can make it generic and have clean conversions
you could even do operator overloads and stuff to make it invisible to get
Ahhh, that brings it down to inline with setting it directly
this + caching GetFieldOffset is about as "safe" and performant as you can probably get it
Ah, I see. The problem is I still need to get/set the value from the fields I don't see how that changes anything
That's also going to be quite allocatey for value types
there are no fields
Since you're boxing them
yeah, obviously you can replace that with a variant
or whatever you want
just sketching it out
So question, would something like lists screw with the offset?
lists are references
Nope
And even if they weren't, that API would still give you an adjusted offset
Otherwise the API would betray its purpose
Oh, see I can't do that. You said it best, it is sort of like UnityEvents. So I can't go around replacing stuff (unless I am misunderstanding waht you are saying)
@urban warren my point is that syncing the fields directly is unintuitive behaviour. It makes more sense to keep a single source of truth for the data
since as you said it's shared
I don't understand the problem
That's good, I was more curious because of caching the offset
Yeah the offset won't change
why can't you replace the fields with a class wrapper
It's a runtime constant
We can simplify it. Just imagine I am creating a 'better UnityEvent' that lets you call methods, set/get property values, and set/get field values
So I want it to work with any existing field/property/method without any modification
I question the wisdom of allowing anything in your codebase to indirectly change anything else in your codebase
This is neat! It requires a external dll thought right? Because of the Unsafe class?
Yeah, System.Runtime.CompilerServices.Unsafe.dll
You can download the package, open the nupkg in 7zip or whatever, browse to lib\netstandard2.0 and copy the .dll and .xml into your project
I would make it an explicit wrapper class just because then it signposts that this value is not controlled by this class
For my use that would 100% defeat the purpose of the problem I am trying to solve by creating this lol
what's the problem?
To let you use an editor to connect systems together. Like lets say you have a cloud/sky system, a foliage shader, and a water shader. They all of controls for like 'wind`, so I want to let you connect all of them together in the editor so one will change all of the others
yeah
nvm then ๐
I would still probably have a central database to manage such values
but then the endpoints would be serialized as references to such and such class and field
so that when you're writing to it you're always writing to the SSoT
That's the plan
Hahaha, I appreciate it though!
@final steeple so like, this is really cool and I am kind of wondering why I haven't seen this before...?
Like it seems to good to be true... like... whats the catch...?
(Also, I do plan on reading more on the topic so I can actually understand better what is going on)
It's just a really low-level thing, and low-level things tend to not be common knowledge
Oh, alrighty then.
Also if I didn't say so already, thank you very much!
Every time I feel like I am getting fairly advanced and knowledgeable I stumble upon a new layer of more advanced stuff and realize just how little I still know haha
It's an endless hole lmao
Once you think you've seen the bottom, you only learn it just gets deeper
especially when you're in a managed lang like C#
you're pretty insulated from the underlying hardware
and data
You say that, and then here I am writing assembly in C# 
haha
butwhy.gif
I was using it for an experiment in doing code injection entirely in C#
If you can output assembly in C#, you can write that assembly into another process
Late-night brain moment, GetObjectHeaderSize can just be
static unsafe uint GetObjectHeaderSize()
{
var box = new StrongBox<byte>();
fixed (byte* pValue = &box.Value)
{
return (uint)((nuint)pValue - Unsafe.As<StrongBox<byte>, nuint>(ref box));
}
}
strongbox is a fun type name
It's pretty handy when doing unsafe stuff with classes
I just enjoy the double entendre
how do yall learn all that unsafe shit
by poking
looks like magic to me
I don't even know myself
Like, I legitimately do not know how I learnt all this stuff
I just picked it up as I went
fair enough
and suddenly had a brain that was 90% unsafe code knowledge
lol
That's just how it goes with stuff it seems
I've lost count of how many times I've posted some low-level code or knowledge and the response is "wtf, how do you know this?"
it's like a code party trick
this happens everytime i post rust code im proud of
but i still know nothing about unsafe lmao
lol
Actually thats probably due to rust
same
i physically recoil in horror at the mention of unsafe code
Hi, I'm rewriting Sebastian Lague's marching cubes algorithms, and I've checked the mesh building pipeline many many times over but can't find the cause of this spaghetti. Here's the two scripts:
MeshGenerator.cs:
https://pastebin.com/aXSekMEN
MarchingCubes.compute:
https://pastebin.com/Wsu8L6DC
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.
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.
The main function in MeshGenerator concerned with construction is UpdateChunkMesh()
Any pointers are much appreciated!
I'm *fairly* certain that the issue lies in the C# code, but I can't figure out where or how to fix it
Is this a good optimization method?
void Update()
{
if (Random.value > 0.95) {
if (!(itself.GetComponent<Animator>().GetComponent<Animation>() == null)) {
if (playAnimation){
if (!itself.GetComponent<Animator>().GetComponent<Animation>().isPlaying) {
itself.GetComponent<Animator>().GetComponent<Animation>().Play();
}
} else {
itself.GetComponent<Animator>().GetComponent<Animation>().Stop();
}
}
}
}
This update method was using 30% of my frame time, so I made it run every 20th frame on average with that random value and now it's only using 8%.
It feels like a really bad practice, but if it works it works...
yikes
Would it not be better to use an actual number to track the frames before it runs all this?
Rather than relying on chance
I hate everything about that snippet
And all those GetComponents, why?
I considered that at first, but then I realized that that would just make it stutter. It would just cause a big lag spike every x frames where x is the value.
If you have a suggestion, I would be very happy to receive it. I've been struggling with performance for the past half day, basically.
Can you suggest a better way? I know there exists other ones but i'm not sure which one we should use.
So now I might get 10 stutters in a row, then no stutter for 100 frames and poor animations?
yes
you can cache the result of getComponent into a variable
GetComponent in Start, cache it into a variable
(He's working with me by the way, just explaining the "we".)
^
Do you not see how that's bad?
cache the Animation. Delete the Animator GetComponent entirely since it does nothing
Will that increase performance by meaningful amount?
Should I just do this? itself.GetComponent<Animator>().Play()
not if you're calling it every frame
GetComponent is not something you want to do each frame, and is really easy to fix
Maybe then you won't need the chance run madness
Well, once at the start I guess.
Is this better?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceSystemAnimationController : MonoBehaviour
{
public GameObject itself;
public bool playAnimation;
private Animator animator;
void Start()
{
animator = itself.GetComponent<Animator>();
}
void Update()
{
if (!(animator == null)) {
if (playAnimation){
if (!animator.isPlaying) {
animator.Play();
}
} else {
animator.Stop();
}
}
}
}
Yeah, avoids the GetComponents
Hmm, I can probably check whether the animator is already stopped before stopping it.
Like this:
void Update()
{
if (!(animator == null)) {
if (playAnimation){
if (!animator.isPlaying) {
animator.Play();
}
} else {
if (animator.isPlaying) {
animator.Stop();
}
}
}
}
Actually, wait, I just realized I can combine those if statements with an &&.
if this is a very hot code path, you can optimize even further by eliminating the null check (are you destroying individual components on a GO that makes this a fear?) and caching isPlaying too in your script to avoid the overhead of another call
It's because I'm using this script with a prefab, and some instances of a prefab are animated whereas others aren't, so I have to do it.
that's when you split functionality
Made it slightly better, I think:
void Update()
{
if (!(animator == null)) {
if (playAnimation && !animator.isPlaying) {
animator.Play();
} else if (animator.isPlaying) {
animator.Stop();
}
}
}
Are you saying I should have different prefabs for every state the prefab can take?
I suppose I can do that, it should only be 8 or so prefabs in total...
void Update()
{
if (animator == null)
return;
if (animator.isPlaying) animator.Stop();
else if (playAnimation) animator.Play();
}
that will permanently stop the animator from playing
itself is definitely unecessary ๐ค
oo, true
or rather it will flicker between stop and play if playAnimation is true
yeah
Look into prefab variants BTW
Although not totally following this discussion so not sure it's appropriate to your use case
I'm guessing this amount of calls is undesirable:
The time it takes it what really matters
Here's the thing:
For anyone out of the loop (I recognize some members that have replied to me a few hours ago), read this message and the five or so after that:
It will be very hard to support big galaxy sizes, if it's barely working at 5000...
Sounds more like a DOTS thing
Ok, so, it used to be 33% of the CPU time without the chance stuff, and 8% with the chance stuff. Now it's 14% without the chance stuff. What if we do both the now better code and the chance stuff?
Yeah, but they are actual textures.
I think it's really just weird to base running that code off chance
Well, is there any other way to spread it out over frames, instead of having all of it run once every x frames?
What's that got to do with the price of fish?
Are you saying each star has this animation controller script?
Wait is DOTS an acronym? I thought you meant that I should handle each star as a dot instead of a sprite gameobject or something.
Yup. Is there some way to make it so one animation controller controls all of the stars, or well, at least all of the stars of a given type?
Because I remember I was able to have hundreds of thousands of cubes all moving in a scene using DOTS
yeah so, this is kind of like trying to make minecraft where each block is its own gameobject
Pretty basic, but fun to watch
at the moment
Huh, that sounds pretty cool, how would I use that?
It's beyond me, I followed a tutorial
ECS is good for simulating many entities. If all you need is to render them, you can do that with your own GPU instancing drawing.
Can I see that same tutorial?
Aaaand there we are again. (Not trying to sound passive-aggressive if it's coming off as such.)
I've come across this GPU instancing many times now, but I can't wrap my head around it.
GPU instancing is something all modern GPUs are capable of. Instead of sending individual draw calls to the gpu for each sprite, you send one draw call saying "draw this star 5000 times" or however many times you need.
Yeah, I understood the basic concepts from the tutorials I watched, but none of them showed how to actually do it.
Well, none of them showed how to do it in 2D - all of them were for 3D.
The code I've found at least requires you to have some kind of mesh, which I don't think I have, and also a custom material which I don't really know how Unity materials work.
Sprites are meshes. You just don't see them when working with SpriteRenderer.
Quads usually, which are just flat squares.
It would be awesome if someone could take a look at my situation (I would be willing to VC + stream) and walk me through it step-by-step. I hate it to be begging for help like this, but it's the only way I see me getting GPU instancing in a reasonable time.
Ero gave you a good way to write your method, but just wanted to add
This is a really confusing way to write this
if (!(animator == null))
Should do this instead
if (animator != null)
Question, does Unity cull automatically?
frustum culling for game objects is supported out of the box, afaik
Nice, I reduced a few more GetComponent calls and the FPS went up even more.
other types of culling depend on many factors
Back to the topic, does it apply to 2D sprites as well?
it should, sprites are essentially 3d objects
Because basically, if I zoom into my galaxy, I don't want it to render all of the stars outside of the view. (Of which there are many...)
how are your stars implemented?
2D Sprite prefab, then when you start the game it goes through the star list of the galaxy object and for every star it spawns a clone of the prefab.
are the stars funtional?
if they are decorative, you can optimize it by using a particle system
They are. Clicking on them pulls up information, and in the future will do other things. (Like double clicking to open the system map for that star and a button to jump your ship to said system.)
that will reduce amount of gameobjects, and render in a single draw call, however static sprites should be dirt cheap to render
monobehaviors receive culling events btw, you can test how they work
I've been told to use GPU Instancing, and from what I've seen it it works wonders, but I don't have any idea how to use them. I've watched tutorials, but they do things that...how to say, don't apply to my situation?
I guess I can try to make them static to see if it improves them at least a bit, as the stars don't move around.
by static i mean just not moving
unless you are using a plugin or you write custom instancing solution the only thing you can do is tick "gpu instanced" flag on the material, but i have no idea how it works with sprites
Oh, lol. Well there's a tick box, might as well enable it and see if it helps.
Same. I can't do it on the default material, and I tried creating a custom one but that halved my FPS and made the textures not render at all.
One benefit of rendering stars is that you don't have to worry about sorting, because they should be rendered with additive blending.
But I'm not sure if you can disable sorting on SpriteRenderers.
You can with particle systems
Assuming I can, how would I do it?
yeah particles are good at solving all kinds of things
bullet holes, footprints, muzzle flashes 1 particle system for each of those
you can set particle data on runtime, as arrays of positions/rotations
depending on how dense the galaxy is you can greatly speed it all up if you ditch gameobjects alltogether
Can particles do on click things?
particles just render
I don't care about physics simulation, I just want them to be things you can click on to pull up a menu and stuff.
@tender badger How long have you been using Unity at this point? This seems like a pretty big project.
you dont need to worry about clicking, if you use particles to render the only change is that you disable the sprite renderers on stars
Huh, that sounds like something.
replace each individual renderer with "render once with particles"
basically manual batching lol
How would I do that?
I mean the actual code, like, what methods/variables would I need to use.
read the api
Do I just search for particles on the Unity docs?
Are you trying to make something like Space Engine?
What kind of scale are we talking about? You talked about generating galaxies. The Milky Way has over 100 billion stars.
There's a randomly generated galaxy, and I took a little inspiration from the GUI, but that's where the similarities end. SE has a realistically sized universe with billions of galaxies, each with billions of stars, as well as kinds of real life simulating and rendering. I'm only generating a single galaxy, based on far simpler math and with little to no active simulation, I'm aiming to have 100k stars be the upper limit (I would prefer 1 million, but that seems like a pipe dream considering anything above 10000 is laggy), and in general the galaxy is supposed to just be the environment for the actual game I will make. (You'll be controlling a spaceship and will be able to do things like mining resources and fight hostiles. It will all be in an arcade-y pixel art style with almost no actual physics simulation.)
So yeah, let's say I would prefer to get decent performance while rendering things in amounts on the order of 100000.
You will need to use the stuff I mentioned that you found too hard to do that, unfortunately
e.g. DrawMeshInstanceIndirect
Or use DOTS and its renderer which is designed for that
Or maybe VFX graph
these are all options
What is VFX graph? I don't think you explained that yet.
This sounds like a very cool game, but it sounds a lot bigger than someone with 1-2 weeks of experience can handle. It's definitely not unreasonable for one developer to make in a reasonable amount of time (it's not like this is No Man's Sky), but only if that developer already has at least a few years of experience. I promise you, a beginner is really going to struggle with this. And this sounds like something you're passionate about, you probably want to see it done properly. I recommend revisiting this idea in a year.
Consider focusing on one smaller aspect of the idea first. Something you can more easily handle.
It's Unity's GPU-based particle system
Yes, that's why I'm trying to get the map to work first.
Is the gameplay loop always zoomed out far enough that thousands of stars are visible on screen?
Would you never zoom into the solar system the player's spaceship is currently in?
How would combat work if the view is zoomed out many light years away?
I did want to make it a continuous map at first, but I decided that that probably would be too complex, so I think I'll probably make the galaxy view and star system view a separate scene.
And double clicking on any star in the galaxy view would open its system view.
Maybe I could even have a fake continuous zoom by making it so that when it loads the system view scene, it zooms in onto the central star a bit to basically trick the player into thinking it's continuous, but it's actually not.
And combat will not be in the map at all, but a dedicated screen. Sooooort of like combat in FTL, but different in some ways.
But if it was in the map, then well, just scroll in.
hey there could someone help me debug something?
I'm trying to make a restart level feature so I suppose the easiest way would be to reload the scene. But after doing that i'm having issues with null references even after removing event handlers on destroyed objects
you'd have to share the specific code and errors exhibiting the issues
Oh, shit, sorry, missed that first message. Wouldn't have needed to type that wall of text if I saw this and just answered no, lol.
basically it says the black holes variable is null when i'm instantiating a new UI everytime the scene loads. That variable is assigned by the editor on a serialized field and works on the first time but not after reload
But yeah, to go back to the main topic, it's not the main view, but I want to finish one part of the game first before starting to work on the next.
you'd have to share more code. Please don't use screenshots. Read #854851968446365696
for example is this object DDOL?
Is it a singleton
even the object "this" is null itslef idk why, if it's the previous instance shouldn't it be destroyed on reload
What about the blackHoles variable? What type is it? Where is it being assigned? Etc
can I go to a call and screen share? would be easier ๐
no
okay
if this is null then your code is running on a destroyed object.
ikr but why? if I remove the handlers OnDestroy
that's the main issue
it sould solve the problem
you haven't shared enough code to make it apparent whjat's happening
Oh
Well I can see right away
your OnDestroy code is not correct
YOu can't unsubscribe lambdas like that
yeah i was thinking about that... my bad. how should I do it then?
You should be doing this:
// subscribe like this
GameEvents.instance.OnBlackHolePlaced += UpdateBlackHoleCounter;
// unsubscribe like this:
GameEvents.instance.OnBlackHolePlaced -= UpdateBlackHoleCounter;```
the way you have it now it's saying "unsubscribe this brand new lambda function" which wasn't subscribed in the first place, so it does nothing
right and i don't need to pass the variable on the subscription? does he know it automatically?
because i'm subscribing like this
no - passing the variable happens when the invocation happens
Yeah I know what you're doing right now - it's wasteful and unecessary
there' s no need to use this middleman lambda function
oh thank you so much, today I learn
and it makes it harder to unsubscribe too
The event subscription wants "a function that takes an int parameter and returns void"
That's what UpdateBlackHoleCounter is
you need nothing else
Awesome, Been doin it wrong my hole life. So if the parameters of my function math the parameters of the event I should subscribe only with method's name
thanks man saved me hours โค๏ธ
lambdas are also okay but if you want to unsubscribe the lambda, you need to store it in a variable so that you're unsubscribing the exact instance you subscribed with.
Using the method directly, where possible, is much more straightforward
Got it makes sense. It's kinda like pointers right? Didn't know that was a thing in c#
Yes, it's a "reference" in C#, as you're not allowed direct pointer access
How do I find the number code for a particular warning?
Is there a site or in the manual somewhere?
wdym? Like CS0343 something like that? Just google it.
those would mostly be C# things not UNity things
Maybe this is helpful too https://github.com/thomaslevesque/GenerateCSharpErrors/blob/master/CSharpErrorsAndWarnings.md
It's not generally helpful I don't think though ๐ค
Well, the warning I'm trying to suppress doesn't have a code, so I don't know what to do
What's the warning
It's SendMessage cannot be called during Awake, CheckConsistency, or OnValidate
Okayyy...
it's a Unity thing
wat do
The way to fix it is to heed that advice
I tried and it broke my code
If you're actually calling SendMessage at all, I would actually recommend against doing that
SendMessage is almost useless for 99% of normal games
Show your code
It's AddComponent<>()
Whatever component you're adding has a SendMessage in its Awake()
I tried using UnityEditor.EditorApplication.delayCall = () => { }; but it chopped up my code and didn't work
Adding components in OnValidate() and then I need a reference to that object before the method ends. Give me a minute for the code
// create a new chunk
if (!chunk_present)
{
Chunk new_chunk = CreateChunk(coord);
chunks.Add(new_chunk);
}
chunks[chunks.Count - 1].SetUp(material, generate_colliders);
I'm running this for every chunk, but it doesn't work on them all when I use delayCall because chunks.count - 1 is taken before the chunk is added
Can we just start over... Here's what I tried:
if (!Application.isPlaying)
{
UnityEditor.EditorApplication.delayCall = () =>
{
// create a new chunk
if (!chunk_present)
{
Chunk new_chunk = CreateChunk(coord);
chunks.Add(new_chunk);
}
chunks[chunks.Count - 1].SetUp(material, generate_colliders);
};
}
else
{
// create a new chunk
if (!chunk_present)
{
// CreateChunk initializes a GameObject and adds the Chunk component to it
Chunk new_chunk = CreateChunk(coord);
chunks.Add(new_chunk);
}
// SetUp adds the rest of the components, like mesh, collider, etc.
chunks[chunks.Count - 1].SetUp(material, generate_colliders);
}
It didn't work for some reason, it doesn't create all the chunks that it should.
I still don't know what this has to do with SendMessage
or what CreateChunk does
or why you need a delayCall
also why chunks[chunks.Count - 1] instead of just new_chunk
OnValidate + AddComponent = SendMessage cannot be called during Awake, CheckConsistency, or OnValidate
show the code for CreateChunk
and show the code for the script(s) on the objects being created
you've shared very little here
hard to help
Chunk CreateChunk(Vector3Int coord)
{
GameObject chunk = new GameObject($"Chunk ({coord.x}, {coord.y}, {coord.z})");
chunk.transform.parent = chunk_holder.transform;
Chunk new_chunk = chunk.AddComponent<Chunk>();
new_chunk.coord = coord;
return new_chunk;
}
Literally nothing special
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.
Can you show the full stack trace of this error?
And both CreateChunk() and SetUp are called in OnValidate
1 sec
Also might be related to this https://forum.unity.com/threads/sendmessage-cannot-be-called-during-awake-checkconsistency-or-onvalidate-can-we-suppress.537265/
SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (Chunk (4, 4, 1): OnDidAddComponent)
UnityEngine.GameObject:AddComponent<UnityEngine.MeshRenderer> ()
Chunk:SetUp (UnityEngine.Material,bool) (at Assets/Scripts/Chunk.cs:48)
MeshGenerator:InitChunks () (at Assets/Scripts/MeshGenerator.cs:368)
MeshGenerator:Run () (at Assets/Scripts/MeshGenerator.cs:90)
MeshGenerator:RequestMeshUpdate () (at Assets/Scripts/MeshGenerator.cs:110)
DensityGenerator:OnValidate () (at Assets/Scripts/DensityGenerator.cs:17)
Ok I guess AddComponent calls SendMessage itself ๐ค
But it points to each AddComponent
that is probably how it calls the OnEnable/Awake methods on the new component
It's new, I never had these warnings in 2019 I don't think
And the code I'm rewriting also only had these warnings when upgraded to 2020
The thing is my code works fine, I just am being irritated by the warning when I adjust the size of my map (creating new chunks)
Can anyone help me here please?
asked in code-beginner couple of times but no one respond.
I am trying to do a multipart PUT request from Unity. any guide or maybe what is wrong with the below code attached.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Anyone have a multiplayer game idea
So I have a scriptable object with a field like in the picture. Everything has been working fine but now I'm trying to make my first build and I get the following.
Assets\RTR\Script\Card\Effect\EffectData.cs(14,16): error CS0246: The type or namespace name 'MonoScript' could not be found (are you missing a using directive or an assembly reference?)
Did a bit of research without luck. Does anyone know what I could do to fix this?
remove all references to MonoScript in scripts included in your build. It's in the UnityEditor namespace
The scriptable objects will still work properly with MonoScripts though?
Cause that's how effects are referenced in SOs
you can't have any types from UnityEditor in a build at all, so no they're all broken
So there's no way to pass a script as a field ever?
Like.. if I generate a new object from the SO and use that, that's fine correct? The only issue is the SO in the build folder?
generate a new object how? In the editor pre-build? Sure. But the type MonoScript literally does not exist in a build, so you can't have it as a field on anything that goes into the build
This was how card effects were definited in my code base, can you think of a simple way to make something like that work without having to redo everything?
That's bad news...
you could probably do some hackery with custom PropertyDrawers to make something similar to the way you're using MonoScript
You might consider rewriting your effect scripts as SOs themselves, and assigning those instead
You create an instance of an SO in the editor but the effect is really just a script (unique code for each). Can you have an SO that you don't "create and instance of" in the editor?
your SO could exist for the sole purpose of adding a specific effect script. You wouldn't need to worry about instances of them if they're just factories
what does your EffectData SO do exactly?
Has data about how the effect is handled, and then the script that contains it's unique behaviour.
I assume it adds a OnPlayDiscoverEtc component to a GO at some point. Does it set any fields?
It does add it to a GO. Wdym by set fields?
where are Effect Target etc used? Do they get applied to the component EffectData adds to a GO?
Some are used as params to call the MonoScript and some are logic within the code before/after it's called.
well, two options are to make EffectData a generic type and define subclasses for each effect script, or you could make a SO for each effect script whose only job is to add that script to a GO supplied by your GameData SO
I was doing research at the same time, and I think there's a way to almost change nothing. If I put a string instead of an effect script and then load them at runtime like this?
Wait.. what about an UnityEngine.Object type field?
I can still drag a MonoBehaviour into it it seems..
that's what your option 1 is doing
Yeah but then the type is no longer UnityEditor.MonoScript, it's UnityEngine.Object.
I'm not sure this will work for you. I have no idea what happens if you try to serialize a MonoScript in this way
Hmmm... I guess it's worth a shot.. it will reset all my SOs though..
The values I mean.
How many do you have? hopefully you didn't wait until near the end to try an actual build :(
I waited 3 months sooo... yeah.
probably worth automating it with an editor script, then
What do you mean?
write an editor script that fetches all of your EffectData SOs and edits them. The laziest possible option would be to:
- add a serialized string to your EffectData SO
- run editor script which grabs all EffectData SOs, sets the string to the class name, and marks them as dirty
- save project
- delete MonoScript field
Oh, good to know that's doable.
New problem though. What I posted above was from 7 years ago and I'm not sure you can add component from string anymore, will look into it.
I didnโt even know you could do this at one point
Hi. I'm trying to implement dash to my object with rigidbody based movements. Is there any good implementation of dash using rigidbody? Or should i switch to transform while dashing?
I tried to actually
But since the object had move pretty fast physically and the dash direction can be in the different direction, the dash can miss the target sometimes
It's a frustum not a fulcrum, but sure https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
Hello. I have a problem. I don`t want my camera to rotate
public class CameraRotation : MonoBehaviour
{
void Update()
{
transform.rotation = new Quaternion(0, 0, 0, 0);
}
}
Quaternion.identity is the default rotation
what you have written is not a valid quaternion
Don't manually create quaternions, even the default one imo
Don't use the constructor at all ๐ตโ๐ซ
I have changed the value, but now it affects the rocket. Probably I am working with the camera wrong way. Could you tell me how is it usually used when you want a camera to follow your player?
Because I have placed the camera inside the player
If it affects the rocket, your script is also on the rocket
on the camera
This really isn't a #archived-code-advanced question. More #๐ปโcode-beginner
Sorry, didn`t notice))
Managers usually needs to communicate with eachother, how would u guys do that connection ?
Singletons are like hack of unity, i dont want to use it trying to find a more acceptable way which i can use on any language or engine
The singleton pattern has nothing to do with Unity
i know but as i said i define it as a unity hack
why
forexample u cant use anything like a singleton on UE
its not the point right, im trying to find more ideas about the problem
thats another way i dont wanna use ๐
Maybe DOTS or OOP can be a better solution, but i try inheritance from base class but im getting nullref exceptions somehow
well i can't think of any better solution here than a Singleton
not everywhere only on same gameobject, those 4 managers manage the single NPC
wait so these are on every npc?
yeah and its not good for optimization
well then Singleton is not really an option if it's gonna be on every npc
just sayin when you use the word Manager in a Unity script it usually refers to a Singleton
Yeah i probably need to find better words,
let me show u guys a bit
Civil is derived from Monobehav...
I also define all managers as public and getcomponents at start;
so i can use any manager from civil
//public class CivilDestinationManager : Civil
But under any manager when they try to communicate eachother i get nullreff like
CivilAnimationManager.doSomething();
Im not bad at OOP designing but couldnt figure it out on unity
Like I said in the other channel, I don't think this is inheritance related but we need more details to give more info
what detail can u need ๐
The ones I listed repeatedly before : /
okay look this Civil class inherited from Interactable its an monobehaviour
This is the animationManager derived from Civil, it can debug xa value as 5, but destinationManager.enabled is "NullReferenceException"
unity (cant or dont idk) pass Script refs on inheritance
Anyone here familliar with UniTask? I'm trying to listen for connections, but Accept() blocks the main thread even though the function doing the listening is being called from a UniTask.Void()
CivilAnimationManager is hiding Civil's Start method by defining its own. That means _civilDestinationManager is never assigned a value. If you want Civil's Start method to run in CivilAnimationManager, you have to override it and call it:
// in Civil:
protected virtual void Start()
{
...
}
// in CivilAnimationManager:
protected override void Start()
{
base.Start();
...
}
What about multiple inheritance , do i need override start on each one ?
Yes.
I got another question about it, can i assing them as _CivilAnimationManager = this ? or something likethat
cause only scripts cant inherited from base Start
On here first log is null, second one is CivilAnimationManager so its looks like working, let me full test
UniTask.Void(async () => await ThreadedNetworkSocket.ListenForConnections());
public async UniTask ListenForConnections()
{
Socket Listener = new(SocketType.Stream, ProtocolType.Tcp);
Listener.Bind(new IPEndPoint(IPAddress.Any, networkSettings.Port));
Listener.Listen(10);
Socket handler = Listener.Accept();
anyone know why this should block the main thread?
Probably parallel and concurrent aren't the same thing
I don't know Unitask but it looks like you're doing concurrent and not parallel
doesnt work like this
regular Task has problems with unity because unity really doesnt work multithreaded
UniTask was made specifically to solve that, but it seems like maybe I need to use regular task for this one part?
A regular task is also often concurrent
well what's the right way to listen for a connection in unity?
// Multithreading, run on ThreadPool under this code
await UniTask.SwitchToThreadPool();
/* work on ThreadPool */
// return to MainThread(same as `ObserveOnMainThread` in UniRx)
await UniTask.SwitchToMainThread();```
From a quick google, you want something like this
Or there might be other methods in unitask to defer to a different thread
ok thanks
You can also just use a threadpool yourself
is something similar to SerializeField available for functions to be used with UnityEvents?
i want to call a function using a button but i dont want the function to be public.
even protected function doesnt show up
Works like a charm, can u explain e why do we still need base.Start(); even we are overriding it ?, also while overriding does base class Start method executes or just ignored ?
Overriding does what it sounds like, completely overrides the base method. If you want the base method to still be called, you have to do so manually.
You should create a UIMessenger class that has all the callbacks for buttons and such. The callbacks would then, in turn, call the actual function
but then the function would still need to be public
if a function is supposed to be called from a button, then conceptually, it should be public. it's being called from another script
so manually executing is base.Start() right ?
Yes.
What about the compiling time, do i generate 4 different civil base classes for 4 different manager derived from it ?,
Shared code will still be shared if that's what you're asking.
Thanks ur answer give me a new perspective about inheritance on monobehaviours
Btw how would u do the connection between managers ?
no. Conceptually speaking, we do have SerializeField attribute which allows us to modify a private variable from outside the script which contradicts this statement.
I prefer to keep the code logics separate from the UI logics and will try to avoid making every function/variable public. I understand that I can still use SerializeField for the button, and then subscribe to the private function from within the script which is totally fine and what I actually do. But it'll be time saving if I could somehow tell unity button to call private methods from inspector (something which Unity itself uses to call Update, FixedUpdate, etc but yes these are not related to Inspector)
I was expecting Unity to have some attribute for it. It would also help significantly more for such functions to have that attribute instead of them being a public function, so that its easier to debug. Its hard to debug a bigger code base when a public function gets triggered (from UI/Unity Events) randomly and you have no idea which function it could be.
Atleast with attributed function, you can simply do a find all reference and then eliminate the remaining possibilities by atleast 50%+
instead of doing it in the inspector, you could add the function to the event in Start()
@reef wren
that would still require me to have reference to the UnityEvent of the button
I'm talking about a normal canvas UI Button, not c# delegates/events/actions
you mean like
myButton.onClick.AddListener(MyClickEvent);
?
Hello everyone.
I am working on an RPG and i hit the wall of my knowledge, maybe one of you can help me out.
I am working on an Ability System currently and i would love to have a whole System to click my abilities togehter.
I was thinking to use scriptable objects but i quickly realised, for damage calculation and on hit effects, i would have to write own classes to implement these things.
Is there a way to build smaller Components and link them in a custom editor or something ?
VFX and stuff will probably be in prefabs so that's not an issue for a SO. Damage Calculation can be done on the SO as well, it's scriptable. You can also link them together, so you could have one way to calculate damage as a SO and another way as another SO for plug and play ability building
If you're going with the SO approach, my best advice is DO NOT STORE ANY STATE INFO ON THE SO. It should only be used to hold references, and process data. Like damage seems fine. Just don't store current health in there or something
its all for server code so i am highly careful on my resource management. But yeah, the ability gets the PlayerStats component to calculate whatever the actual damage is (str increases melee dmg and stuff)
The plug and play thing sounds interesting and exactly what i was looking for. Can you go into more detail? I used to use an old unity version for way to long so my knowledge with SOs is quite limited.
Sounds good about the playerstats component feeding it data. I would make sure you stick to basic data types for any sort of networked code as well. You may need a separate SO for Network info or something, and have it as a child of a bigger SO that contains VFX references, etc. I'm not sure, just an idea
With [SerializeReference], you can easily write small classes and serialize them through a shared base class. You just need something to handle the GUI of selecting the types in the editor, like this package:
https://github.com/mackysoft/Unity-SerializeReferenceExtensions/
I'm running into issues trying to integrate mirror because I have non basic types in my ability SOs, figured I'd mention it
its a fully closed authorian server. So i dont need to worry about datatypes on the backend. In the best case, only the instantiate of the ability will get called on the frontend and there a simple ref should do the trick. Once i have this ability mess running
using mirror myself, if you need help, maybe i am your person!
Might have to remember that
waaait a minute ... this looks amazing and like the exact thing i need i think. Thank you so much i will read through it!
Stable's idea is good, and I believe I wrote a script that helps with that for a modifiable stat system I abandoned a while back, might help
Been a while though so don't remember how it works, might be useful though for selecting. In this case I'm using it to select stats from a dropdown iirc
you two are a massive help. Thank you. This means i spend a lot more time to get it going but it seems like a proper longterm solution
i need to completly overthink how to get the stuff done i have in mind but this tool seems like the right way
Finally solved that damn material problem I had
For anyone interested:
Use a hashtable and iterate trough all the objects that have the materials you want to swap for a highlight.
convert that hashtable to an array.
Now every renderer has to compare each of its materials to the materialarray and write down the index numbers.
When changing from a highlighted material back to the original you can now use the index numbers.
You can do that in the editor, no need on awake or runtime.
With that you can now use sharedmaterial, since unity doesn't instantiate materials anymore.
So happy that sht now works
Is there a way I can move physics objects around the player. I have a big world and I am worried that our near the edges Iโll start getting floating point precision errors. So the solution is to keep the player at 0 and move everything around the player. However, my world has physics stuff in it, and if I move those Iโm worried it will mess up the physics simulation. Is there a way I can do this?
Alternatively, how far out from origin do things have to be for the jitter to start being noticeable? Maybe my map size is within that bounds.
You can move the whole world regularly back to origin if that helps you
Other than that you could section your world in levels and after async loading each level you move everything to origin
Something like that:
Okay, so I have an implementation of the a* algorithim that uses two or three scripts. Pathfinder.cs which has the primary method FindPath(PathNode start, PathNode end), and PathNode.cs which gets generated per tile at runtime in the TilemapHandler.cs script (which is responsible for perlin noise generation) and held in a list using the class PathNodeManager.cs. As to my tilemap, its a multi layered isometric z as y tilemap.
The issue I'm having is that my algorithim wont find neighbours, when i know for a fact that that list that is being checked against with .Contains(PathNode) contains the path node being checked. I have no idea why this is happenning but it is, and subsquently paths aren't being found. There certainly are paths, as obstacles (a bool IsBlocked) are set at tilemap generation using an if statement that checks if the tile is null (true for empty tiles like in tilemap 0 which is the plant layer), and if it isnt, the bool is set.
[Picture of the test tilemap]
https://pastebin.com/vmJDTSvg -- Pathfinder.cs
Why does a headless (batchmode) Dedicated Server build generate shader errors and warnings?
What do they say?
Yeah, I don't have anything to offer other than it looks like it doesn't like your GPU. Might be ok if they're just warnings
If you're missing shaders, sounds like there's a fallback option you can enable
Yeah. I thought of those things too, which lead me to ask the question why is it even doing anything with the shaders if there's no rendering (batch/headless mode).
Thre's also a separate -nographics argument
that might be relevant
I was under the impression that those arguments aren't needed with Dedicated Server builds. That it was built in. However, upon looking it up (to see if my assumption was correct), it seems these shader issues are a known issue.
https://forum.unity.com/threads/unity-2021-2-dedicated-server-target-and-stripping-optimizations-now-live-please-share-feedback.1143734/#:~:text=Starting in Unity 2021.2%2C when setting your platform,to apply these optimizations during the build process.?msclkid=f55b8254ae3211eca6b8ad65fa26e001
Oh you're using the new dedicated server target
nice
I guess it still has some kinks haha
You shouldn't need to sync SOs over mirror.
You can include them in the build and give each one a unique ID which is sent if necessary
Yeah I was passing them as a parameter and needed them to send a message and it failed iirc
I do already have a SO "DB" with all of them, for a good unique ID and lookup
Can anyone teach me how to put a gun in my 3d game?
Download gun model, drag in Unity. Then drag it into the scene
I think you're in the wrong channel.
ah right right.
Perfect
How could I learn to implement a reversed-z camera?
A camera with a reversed-z Depth Precision buffer
do a standalone build and start with -nographics -batchmode instead
unity cannot prove a dedicated server build will work for a given list of unity scenes so don't use it
it is a set of heuristics not something that Makes Sense
why didn't you use a material with a property?
hmm now my a* algo returns so many neighbours that it infinite loops. and the closed list just continues to build in some random direction. i must've messed up the code somewhere
You should be ignoring any nodes you've already visited
I think I am
an issue is that the closed list spins in circles and doesn't actually find a path
so the algo must not be implemented correctly
If it's going in circles it's revisiting already visited nodes
yeah i guess you're right eh
it really shouldn't be happenning tho
the starting line in the for neighbours loop should negate it
foreach (var neighbour in GetNeighbourTiles(currentPathNode).Where(x => !x.IsNodeBlocked && !closedList.Contains(x)))
What kind of objects does GetNeighborTiles return
I.e. how are you representing your nodes
as a PathNode object with an x, y, z, and a g, h and f cost as well as a bool for IsNodeBlocked
What's PathNode look like? Is it a struct? Class? Are the instances reused? Is there an appropriate . Equals method?
i think the way i was checkign neighbours and addign them to the list was bugged
cuz it was instatiating a new path node
i changed that to
this
Vector3Int locationToCheck = new Vector3Int(currentPathNode.GridLocation.x + 1, currentPathNode.GridLocation.y + 1, currentPathNode.GridLocation.z);
if (map.cellBounds.Contains(locationToCheck) && !closedList.Contains(GeneratePathNode(locationToCheck)))
{
neighbours.Add(pathNodeManager.pathNodes.Find(x => x.GridLocation.Equals(locationToCheck)));
}
i might remove the !closedlist thing since that was from before (and it didn't do anything anyway as that check is already perfomed earlier)
hmm now im getting a nre from linq wtf
What does .Find() do? Would .First() be a better choice?
Looks like Find is FirstOrDefault but for lists
Hello,
I am working on project where i used newtonsoft plugin for unity, turns out plugin had problems when i build project on il2cpp and was failing some tasks, now i am trying to find way to invoke methods recived with signalR, before i was using cast to JArray, but now i dont have that luxury, I am getting this kind of objects/Lists which has method name at first place, then parameters.
you mean like switching it so in the shader it gets switched?
I have it on a small shader but it is not always the fastest way, esp when you want to highlight multiple objects that have different shader. It is then faster to switch the material.
Also it is a better system for designer because creating highlightmaterials and saying which thing gets what highlighttype is much easier.
Does GPU Instancing improve the performance of animated sprites as well?
Let me rephrase, what ways are there to optimize large amount of sprite animations? I imagine that it would be different from optimizing the sprites themselves.
Are you trying to use dynamic?
im trying to have a scriptable object remove itself from a list after a timed duration of turns, yet for some reason it wont? What am I doing wrong here?
There could be many thing here around when what parts of this are called etc., but one problem that jumps out to me: If CH.CE is some kind of List, then RemoveAt will change the indices of all other entries after the one you remove in the list. If you don't update their Place field at that point, when they later try to remove themselves, they'll use an incorrect index
hmmm, that is true. Do you have any suggestions on going about this?
Yeah this.
If you just want to remove yourself you need to re-compute the other's indexes, OR...
The easy solution is using Remove instead of RemoveAt :)
Remove yourself CH.CE.Remove(this);
(Unless Place is used by other things too and needs to actually be correct; in that case you won't get away without updating indices)
aaaand now im getting this
this is how the character handler handles the condition list btw
Ah yeah, if you're iterating over the CH.CE list while removing you can't
With foreach at least
You can use a for loop yeah
Reverse for loop to be precise
So removing an element won't mess with the indexes you're going to remove in the next iterations
like this?
That condition looks wrong
It is wrong
i >= 0
if i'm not mistaken
what you have written there will only do 1 iteration on index 0 @hushed sparrow
well what's written is a syntax error
but if the rogue > is removed then it iterates either 0 or infinite times (or at least until integer underflow)
when am pressing esc in playing sun temple asset...it pauses the game in unity editor and even if we change the scene on ESC then also game is paused in that scene also...how to solve this issue
this goes on way too long, i think ill keep it to <=
since its going reverse it just needs to check each time if its at or below 0, not above it
otherwise yeah it goes on infinitely
If you keep it at <= 0 it simply wont run, or if CE is empty, it'll run infinitely
<= 0 is just wrong
then what should i change it to?
it has to wait until its less than or equal to 0, what am i supposed to put there?
im trying to go from the last to first item of the list to activate its functions seperately for handling status conditions
usually your ide has a utility for reversing a for loop
It's a reverse for loop
but it looks like this:
for( int i = CE.Count - 1; i >= 0; i--) {
}```
nope, need to sub one from CE.Count when assigning to i
Oh, right, mb
cool beans
how do I make my enemys
in my game attack me
Have you tried insulting their honor?
lol
yep they just staired deep into my soul
Is there a way to script two different, identical animators to be "equal"? I have two identical objects, and when one runs its animator, I want my script to read that happened, and tell the other animator to do the same thing
A few ways:
- Just have the code that starts one animator start both animators instead
- Have the code that starts one animator invoke an event, and have another script listening for that event and start the second animator
- Make a StateMachineBehaviour on the animator that listens for the entry into a particular state, and starts the second animator
alright, thanks
I honestly don't understand why Unity doesn't have a function that allows you just to jump into your game like Unreal does.....
The play button..?
It doesn't allow any form of control, as in you don't have a mannequin or something to control via wasd
ye you need a move controller for that kind of direct control
Unreal Engine is designed primarily for FPS games and gives you a default FPS character to control
Unity is designed to be more open ended
in any case you can just use Unity's standard FPS controller and get that same thing
as a new user who is making a level, how does one explore it using some sort of reference model or object to test scaling?
You're thinking about it backwards. You need to create your character first. This is a case of Unreal prescribing to you what the size of a character should be etc and then you building your level around that
Maybe not everyone has the same sized character
not every game is an FPS
it's too in-the-box
so how could i visualize the path nodes? its a pure class. more debug.drawX?
(i already used debug.draw line to draw the path)
which isn't optimal but that can be changed lol
(also ignore the nre, its due to the town name being null -- ie you cant set the town name if you jump straight into the scene)
I attempted to add in a FPS starter asset and it already has script errors
which one
this is not from the package you just linked
Standard Assets is a much older, very outdated package
This is the contents of the one you just linked
none of them are a folder called "Standard Assets"
how would I go about removing that package then?
Just delete the "Standard Assets" folder
Is there some kind of way to dynamically generate a mesh out of individual parts?
I'm slooowly starting to get the hang of GPU instancing, I think, but the problem is that every sprite drawn has to be the same. (Though I've noticed that it still let's me vary the size.)
Now, it's the draw calls that cause performance issues, right?
GPU instancing is one way of reducing them by combining a bunch of similar ones into a single one, but how about somehow taking a bunch of different sprites, and combining them into a single draw call?
I'm only really looking to change the color, so if there's some way to do that with GPU instancing I would take that as well.
Is there a clever solution for a unique ID system for Scriptable Objects? I have like 100 SOs of one type and i would love for them to have all a unqiue ID. I am certain there is a way to get it done but i dont find a good clever solution
You can't number them?
When i number them by hand i will at one point make a mistake so i would love to have an automated system do it for me.
I could add an editor script that finds all SOs of the given type and gives them an ID but, if i could, i would love to have an OnCreate event that does this stuff for me. Is there an option for that? My experienmce with SOs is quite limited.
I'm thinking about using a particle system where the particles are just a glow with a color and have the same positions as the sprites together with the instanced but uncolored sprites for this. Hell, if it's allowed, I could literally make the particles the same texture (but colored of course). (In case you wonder why I don't just use particles to begin with, I need the objects to be interactable.)
okay my question was dumb, sorry for bothering you all! Google found the solution rather quickly, sorry agian for asking
any thoughts on how i can get my generated pathnode grid (dots) to align with the isometric grid (tiles)? some sort of maths im guessing, maybe matrices idk
actually i found a video thats really useful so far (https://www.youtube.com/watch?v=04oQ2jOUjkU)
Isometric games often use hand-drawn 2D sprites to add depth to a game without having to deal with full 3D rendering.
In this video, I cover how it works, the math you need to render isometric sprites on the screen, and how to find the isometric tile from a screen coordinate.
Music: Snake Hips - Lucas Pittman (via epidemicsound.com)
goes into the math needed to translate the position from XY rect to XY iso
How can I find the distance between two points on a custom axis?
I used the Plane class to calculate it
So the vector.project function doesnt retain all magnitude?
weird, i had a formula that was literally just working 10 mins ago and now its doing this weird line thing
it was generating a isometric grid of dots but now it generates a line going from top right to bottom left wtf lol
back to square one i guess
does anybody have a formula for linearly transforming a set of cartesian coordinates to a isometric equivalent?
nvm lol
What the hell...
So, it looks like I'm finally getting the hang of instancing, but there's still some issues.
For some reason it's not instancing every once in a while, which kind of ruins everything.
looks like you're drawing both instanced and non-instanced
Unity seems to be able to support up to 512 draws per instancing, but on average around once in 50 gameobjects it just refuses to instance it, which restarts the instancing process.
It's seemingly random. The first instance has 46, the second one 29, the third one 42, etc.
I know, but I'm wondering what's different about these that they don't automatically get instanced.
does the reason tell you anythign useful
in the frame debugger they usually tell you why something wasn't batched
"Rendering different meshes or submeshes with GPU instancing"
Ok, this is extremely sus.
Notice how it's usually one set of instancing, then an individual one, the next set, etc., but then at the bottom it's two instancings?
If I click on the bottom-most one, it tells me that the previous one was reached the maximum instance count.
Now, this is very strange, because the one above it has only 16.
But then I counted all of the ones from the start up to and including the one that has 16, and it gave me 502. Nothing weird about that number, right? Well, if you count the individual ones, it's ten, which combined with 502, leads us to exactly 512.
If so, why aren't these just in one instance?
I was actually going to ask you to do just that haha
Those things are generated in a loop from a prefab, and the only thing that changes between them is size, position, and some values of a script component. If those things prevented it from batching, then none of them would be instanced. Yet most are, and it's just those few that aren't.
The threshold at which inefficiencies begin depends on the GPU, but as a general rule, donโt use GPU instancing for meshes that have fewer than 256 vertices.
Interesting note on the docs page
Well, that shouldn't apply, because even the one with only 46 instances has 368 vertices.
Even then, that would just be a performance/framerate thing, and it shouldn't influence how the CPU instances things.
@sly grove I've talked to about GPU Instancing a few times now, do you know what may be going on? This is so cursed.
So I go from general over to here. Maybe thats the better channel. I am trying to get a public list as dropdown in other classes. Because of not being compiled, I only get a null reference from that list while accessing it.
post code
public List<UIPages> linkablePages;
this is in class A, I want to get this into class B as a dropdown
[CustomEditor(typeof(UIButton))]
public class UIButtonEditor : Editor
{
private SerializedProperty allPagesList;
private ReorderableList charactersList;
int index = 0;
string[] pageNames;
void OnEnable()
{
allPagesList = serializedObject.FindProperty(nameof(AppManager.linkablePages));
pageNames = new string[allPagesList.Count];
for (int i = 0; i < AppManager.AllPages().Count; i++)
{
pageNames[i] = AppManager.AllPages()[i].name;
}
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
index = EditorGUILayout.Popup(index, pageNames);
var someClass = target as UIButton;
// Update the selected choice in the underlying object
someClass.buttonTargetPage = AppManager.AllPages()[index];
// Save the changes back to the object
EditorUtility.SetDirty(target);
}
}
this is where I went so far, but its not working because of my static list is always null
Yep, dropdown in inspector
what static list
The AllPages() is basically a static return of the public list
what public list
where do you initialize it?
you said it's null? That should be easy to rectify
So, the public List<UIPages> linkablePages is just inside a manager which I feed with drag and drop.
Now I want my other class to access this list. The static return and the code above is just my current state while trying to figure it out. I dont need the static if I can just link to the public List. Thats where I am stuck now
how many bloody pages lists do you have lol
what does any of this have to do with the one line of code you posted at the beginning
Class A is a basic Mono Script, same goes for Class B
which line is erroring, this one?
someClass.buttonTargetPage = AppManager.AllPages()[index];
Actually as soon as I access
EON.AppManager.AllPages();
I get a null error
sounds like it's coming from inside AppManager
public static List<UIPage> AllPages()
{
if (instance)
return instance.linkablePages;
else
return null;
}``` This is the code for the list. I execute in edit mode the OnEnable and the static List
instance is probably null then?
I am actually not sure. I am not familiar with Editor scripts so far. Let me check
null errors are pretty easy to fix
just track the null back to the source
then check your assumptions and track it back to why it's null
then make it not null
Okay, so instance is null. I guess its null because onenable is not called from editor mode, even with the ExecuteInEditMode?
yeah I wouldn't trust onenable in edit mode
But I guess I am just using this wrong, ExecuteInEditMode can't be used on single functions, correct? It has always to execute the whole class
Okay, I guess thats where my confusion came from. Thats totally logic that both list and instance will be null. Thanks a lot for pointing me in the right direction ๐ I guess its not advanced then anymore, as the rest should be simple editor code ๐
yw
So this is working now, but one issue I got is, that my prefab is in prefabmode resulting in scene mismatch.
[CustomEditor(typeof(UIButton))]
public class UIButtonEditor : Editor
{
int index = 0;
string[] pageNames;
void OnEnable()
{
pageNames = new string[AppManager.instance.linkablePages.Count + 1];
for (int i = 0; i < AppManager.instance.linkablePages.Count; i++)
{
if (i > 0)
pageNames[i] = AppManager.instance.linkablePages[i].name;
else
pageNames[0] = "No page";
}
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
EditorGUI.BeginChangeCheck();
index = EditorGUILayout.Popup(index, pageNames);
if (EditorGUI.EndChangeCheck())
{
var someClass = target as UIButton;
if (index > 0)
someClass.buttonTargetPage = AppManager.AllPages()[index];
else
someClass.buttonTargetPage = null;
EditorUtility.SetDirty(target);
}
}
}```
I guess its a prefab constraint and therefore not possible with this approach
so right now im generating a grid of path nodes (tiles that signify a moveable area) based upon these generated isometric tiles tile.x and tile.y position but its much too large, using 2 units of directional movement instead of 1. (ie the bottom node from the origin generates at 0,-2 instead of 0,-1)
the center grid are the re-arranged nodes position that im after, and the outside grid is how it generates
public Vector2 TranslateToIso2(float x, float y)
{
float newX = x - y;
float newY = (x + y);
return new Vector2(newX, newY);
}
and this is the method im using to translate the values
i figured it out, i had to do this instead:
public Vector2 TranslateToIso2(float x, float y)
{
float newX = x - y;
float newY = (x + y) / cellSizeY; // in my case this was 0.577
return new Vector2(newX / 2, newY / 2);
}
Hello, I want to ask something about Unity Standalone Build. Is Unity doesn't support borderless windowed when build? I read the documentation about FullScreenMode.FullscreenWindow https://docs.unity3d.com/2019.4/Documentation/ScriptReference/FullScreenMode.FullScreenWindow.html
But there is no way to change the resolution of the window at runtime without scale to fit the entire display screen. How I can achieve that? Is I must use user32.dll and handle the window on my own?
Sorry for my bad english
Hello all, I'm running into an issue related to reflection. I think I'm close, but it's running into a ReflectionTypeLoadException error. Essentially, I'm trying to look at all of the loaded assemblies and if it detects a class that is a subtype of another specified class, I want to add it as a component then be able to reference the methods and properties within.
So I have this code here, which works great when there is only one assembly with a class that is a subtype of SkModules.SkBaseModule. But if another assembly is loaded that contains one of these classes, it throws the ReflectionTypeLoadException error and skips the class, but still loads the other expected classes from within the assembly that is doing the checking. Does anyone know what I might be doing wrong?
private void RegisterModules()
{
//Assembly ourAssembly = AppDomain.CurrentDomain.GetAssemblies().
//SingleOrDefault(assembly => assembly == typeof(SkModules.SkBaseModule).Assembly);
foreach (Assembly ourAssembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] theseTypes;
try
{
theseTypes = ourAssembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
theseTypes = e.Types;
}
foreach (Type tclass in theseTypes)
{
if (tclass.IsSubclassOf(typeof(SkModules.SkBaseModule)))
{
Component module = gameObject.AddComponent(subclass);
SkModules.SkBaseModule moduleTyped = (SkModules.SkBaseModule)GameObject.FindObjectOfType(tclass);
moduleTyped.CallerEntry = new SkMenuItem(moduleTyped.CallerEntry.ItemText, () => menuController.RequestSubMenu(moduleTyped.FlushMenu()));
menuOptions.Add(moduleTyped);
}
}
}
}```
why are the types failing to load? Do they have a dependency on another type that wasn't loaded?
Oh interesting, I hadn't considered that option. Let me verify
also based on the docs for ReflectionTypeLoadException, your code probably throws nullrefs
Okay, I think your initial assessment was correct. Going to attempt to load these dependencies properly. And thanks for the call out, I'll review the docs
That was correct, thank you! For some reason it wasn't showing the full error code, I'll have to review what was suppressing it. Still not loading the other classes though, for some reason. But now that this error isn't a stopping point I can continue debugging.
below is my node grid (green = empty space, red = obstacles) and the blue line is the janky path
the pathfinding isn't not optimized. beyond calculating a tenative g cost as a check when f cost is basically the same, how could i go about optimizing this? just hmu and ill show code
is there any way to use TextMeshProUGUI font replacing without placing materials in the Resource Folder ?
i am patching font style with my addressable now and by putting them into addressable means this can no longer be patched and they are shipped with APK
how to get SceneInstance of current scene guys ?
to get currently active scene SceneManager.GetActiveScene()
hello i need help
code length is 700 lines
is there anyone that can help me
i have been strugling for few days
here is the code
#854851968446365696 to correctly share code
you think an 800 line block of code should be just pasted into discord?
and here is the error i get
i did it from this site
#๐ปโcode-beginner this is far from an advanced topic
ok
Getting an error with no call stack and no obvious source (also nothing visibly wrong, I just want a clean console). How am I supposed to track this down?
Graphics.CopyTexture can only copy between same texture format groups (d3d11 base formats: src=21 dst=53)
Hey yall, I had a question. I am planning out an isometric game and am wondering if anyone know the best approach to creating the tile. I initially created an isometric tilemap that randomly generates at the start, but I want to add animations to the tiles on load/unload so I am thinking of transitioning from tiles/tilemap to a programmatic grid/prefabs. Is this horrible for performance?
Probably should have thrown this question in code-general/code-beginner but there were already people asking questions there so I figured I would not throw a chunk of text in the middle of their convo ๐
visual studio has delay showing this
. I have to wait about 2 seconds to Alt + Enter. It's annoying. how to make it immediate?thanks
Probably yes
Is there a better alternative if I want to add logic/interaction to my individual tiles?
The tilemap does not seem to fit my needs, unless I am missing something. It seems like the tilemap is great if you are just painting static images and giving them colliders, but for my game, I want the tiles to be dynamic, interact with the cursor, load/unload based on camera position, etc (there will not be more than like 24 tiles on screen at a time)
how do I use ECDsaCng in unity?
apparently System.security.Cryptography doesnot have that
I'm trying to implement this javascript code in unity C#
Idk about tilemap that much but it should also only render the visible tiles
No idea how to do dynamic stuff with tilemap but I'd guess it's possible
Ok, I will look into tilemaps more then before creating my own grid, thanks for the speedy response ๐
tilemaps aren't so bad. i dynamically generate a 249x249x6 layers tile map with perlin noise and the perfomance is aight with 32x32 sprites
heres a relevant screenshot
the red and green dots are pathfinding nodes which are also generated
Awesome! That is very similar to what I am looking for! Creating an isometric game myself as well.
i used some tutorials for a* and for perlin noise, i can link you the code if you want
Ya! If you can link the a* vid that would be great.
So I am ready to start implementing an ML Agent in my game (Puzzle Fighter clone, fyi. Think tetris but color matters). I plan to use the bot I made to evaluate the Agent's moves, that part I think I'm good on. I guess my question is, what GameObject do I attach the Agent to? I have a GameBoard GO that is responsible for spawning pieces, and the conventional bot sits on that. I have the Piece GO which is what the player controller sits on and is what the agent will control. The only reason I am reticent to put the agent script on that is because the piece gets destroyed when it touches down on the board. Is that a problem?
Here's the current bot playing
anyone know what's causing this error?
you generated a method with intellisense but didn't fill the method out?
the line from the MS docs is
throw new NotImplementedException();
where do I put this?
could you give the link to the docs page
thats the line throwing the error, and which you need to remove.
just google the error and ms docs
uhh
this is the code
in other thread you clicked on it and it said file not found right? it probably doesn't exist yet tbh
yess
so in other words, you cant use it because it doesnt exist
maybe, if it exists lol
are you on windows? lol If possible can I get the dll
i dont use cryptographics libraries
the agent should live on a utility game object whose lifetime is the same as the game
im writing a game that allows modding in xml and c# lol security is so far from that
So the gameboard is fine?
lol, but please could you check this path C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Security.dll
i would create a game object at 0,0,0 named "MLAgent"
and attach the scripts there
no
ok
im busy lol
ok np :p
can you currently run your bot without a unity scene at all?
this is essential to the next steps
of developing a deep learned agent
Uh hmm I'm not sure what you mean without a scene
your game has to exist, essentially, as a pure C# function of the form
[Pure]
(IGameState gameState, Metadata metadata) Transition(int action, IGameState currentState) { ... }
this function and anything it calls transitively (which by definition must also be pure) must not use anything in the UnityEngine namespace
the best implementation of IGameState is a struct with fixed arrays, which i believe you already made
since your game doesn't interact with PhysX, you should be able to author this function without using UnityEngine
I haven't seen anything about these requirements in the unity ml-agents documentation
you can find the library online that provides Vector3 but even that i would avoid
ml-agents is flawed
how so?
any thoughts on how i can optimize my pathfinding beyond checking if (neighbour.GCost < currentNode.GCost) { //do stuff like reroutign the path }
the straightforward answer is that interacting with a unity scene is too slow to train a deep learned agent
relevant screenshot (blue line)
the philosophical answer is that ml-agents is designed for a very specific fake problem, where you set up something that is a potemkin village of a real problem, hide the exact answer for a brute for search to find, and eventually it does find it and it "works"
that is why there is no impactful published literature with ML-Agents
or bots for that matter
it kind of sets you up for failure
if you follow what it is designed for
I mean I could rewrite a bunch of stuff but I went into this with the assumption I would just use ML-Agents
it's designed for creating demos
you can still use ML-Agents
but to create a competitive bot, it doesn't help you
it can get in the way
What do you mean by competitive?
a deep learned bot that plays well
that can defeat your heuristic bot, for starters
you're going to discover that ml agents is too slow to train against the heuristic bot
as your bootstrapping step (that's why you authored it)
why not use utility ai + finite state machines (stuff like monte carlo tree search) ๐
his heuristic bot is a monte carlo tree search
that evaluates 100% of the expansion up to a certain depth ๐
thats sick
it's more like a monte carlo brute force search
hahhaha
The current bot cheats though, so it probably would be better than an ML agent, but that's not the problem I'm trying to solve. I want a bot that is lightweight enough for platform independance. Current bot is too slow and CPU bound, it will play stupider the slower the system it runs on
i don't know if puzzle fighter tells you what the next piece is going to be
The current bot cheats though
you mean because it knows the next pieces?
the alphago bot, which was more about the IT of botmaking than the bot itself, didn't have to predict the future
this is okay imo
you're not doing a research project
getting it faster is really important
making a "pure" implementation will make it a lot faster
the way these deep learned bots work is very sensitive to how the game state is represented
I agree that why I designed it that way but I designed it mainly as a training aid
so alphago worked because Go boards already look like matrices
you can evaluate the rules of Go as matrix math
i'm not saying you have to cross that bridge now
It "works", but it works on an i7 oc'd to the gills lol
but consider they used like a megawatt of power an hour for two weeks to train the bot
or something obscene (and completely deflationary) like that
dayumn is that alot it sounds like alot
you will need the pure implementation because, for the purposes of figure out what is working
you're going to start with a puzzle fighter board that is
It's a lot but I think this game is much much simpler than Go, honestly
5x5 large
puzzle fighter is a lot more complicated than go to a computer
go is simple in ways that mattered to their problem and the mythos around it was a big lie
you can express the go rules in matrix math
it's like it's purpose built for deep learning
evaluating frame by frame in the unity scene is going to be way too slow anyway
but i think you'll cross that brdige
like you can make a version that works with a 3x3 board or whatever
like as small as possible
so that you're not sitting there twiddling your thumbs
there's a lot to "prove"
on your journey to a bot that can at least be trained correctly without exceptions
ok well... I can sit down and play puzzle fighter at an above average level with minimal prior experience. I'm straight terrible at Go. That's why I think this will be easier
lol
I'm certain I could train an ml-agent on a 5x5 board very quickly
there's a lot of "easy" hiding inside games
that's the best strategy then
start with smaller boards
5x5 the current bot can solve 4 deep in less than 50ms
maybe that's all it'll take to make slow things fast for now
like take the starcraft bot deep mind developed
there was a lot of hand wringing trying to explain that the bot did not have superhuman dexterity or whatever
but in real competitive starcraft 2, you only need to have excess dexterity compared to your opponent, not superhuman dexterity, and only for like 5 seconds out of a 15-30m match, to win
which if you watch their carefully scripted demos that's exactly what happens
the bot has better dexterity for 5s, and then the human expert concedes
it is still a huge achievement scientifically
but the game could have removed all of its basebuilding stuff
you are blowing my mind with all this info