#archived-code-advanced
1 messages · Page 147 of 1
you can use player prefs
use mudbun or clayxels for this kind of stuff
don't create your own geometry engine
you can also use Realtime CSG if you want a free asset
realtime CSG supports calculating a BSP-style enclosed space
it's a little shaky what you're trying to say though
it sounds like you haven't decided what exactly players will do. i'd suggest looking at that steam game with the siege engines
Besieged
as an excample
Good morning, I need help with Editor Code, How do I register, a mouse over event? for example, when you mouse over a button, it lights up even without you clicking them. I can change the styles of how that displayed, but what I am interested in, is registering to such an event, including when the highlight turns off when you no longer mouse over.
this is all in relation to editor GUI
not sure if this is considered advance
thanks bro, let me try that
this is what I was looking for, thx bro
Mesh Vertex Color getting stripped after compiling to AssetBundles, and using it for a shader.
How do I force the vertex color to stay?
Already tried enabling R/W
2020.1.17f1
There's an option for that in Player Settings.
https://docs.unity3d.com/ScriptReference/PlayerSettings-stripUnusedMeshComponents.html
It's called "Optimize Mesh Data" in the editor
Has anyone switched to 2021.2 yet? I'm getting "Unexpected node type." errors when building, playing in editor, or compiling scripts. The errors during building cause the build process to fail.
Yeah we looked at this solution and it simply tanks our performance/memory due to this affecting ALL meshes (To completely unstable levels). We just need it for this mesh.
I can only think of a dirty hack, which would be to make a prefab with this mesh and uses material that uses a shader that reads vertex colors, and either reference prefab that in some scene somewhere or put it in a Resources folder so it's included in the build. That will make Unity think this mesh can't have its vertex colors stripped.
I made a class inherit from Component, but cannot add it to a gameobject
public class HackableObject : Component
{
public Action[] Action { get; private set; }
public void DoThing()
{
//dothing
}
}```
I get the error it has to derive from MonoBehavior, but I thought Component also could be added to a gameObject
the message is clear, why are you asking?
Yeah I know it can be fixed by changing it to Monobehavior, but why cant you add a Component as, well, component
because Component doesn't implement all the expected behaviors of a custom script class? it's just designed to be the base class
I would guess there are non-script internal components which implement something other than Monobehaviour, but I haven't looked too closely at it
Transform for example, is a Component but not a Monobehaviour
Hello
I want to know if there's a way to create like a continuous integration for Android/IOS builds
It's my first doing any continuous integration so if there's an example project on github or any tutorial can you share it with me please?
Many options;
You can use solution made by Game CI:
https://github.com/game-ci/unity-builder
Otherwise there is also Unity hosted one if you have Unity Pro/Enterprise
https://unity.com/products/unity-build-server
Or you can use your own homebrewed solution using something like CircleCI/Jenkins/Github Actions, together with running Unity in Batch mode.
This requires a lot of boilerplate though...
I would simply start by learning how to start by making a batch script that does the build for you and then slowly move that to into a CI system. And then from there build auto pulling from your version control. Etc. etc.
Yeah I was going into those solutions as well. Currently just taking this specific mesh out of the AssetBundle. Will investigate this later!
Thanks 🙂
Hello, I have a project I'm working on that involves a data type that has two different human-readable interpretations. One is the base value, and the other is a stringified representation, kind of like this:
MySpecialType x = 1
((int)x).toString() //1
(string)x //"one"
I have implicit operators to convert between my primitive types, and would like an inspector that would allow me to edit either the string value or the int value, and adjust the other one while it's being set.
It's a struct, and I'd really like to keep my base classes as separated from unity's wrappers as possible, so I've created a PersistedMySpecialType that I can instantiate as a prefab, and it has a string field, and I've been able to mostly get the inspector working as I'd like, but I'd really prefer it be a property drawer so I can edit the persisted instantiation inline. Does anyone know if there's a way to associate two input fields to a common base field through a property drawer?
If I make the PersistedMySpecialType extend UnityEngine.Object, I'd have to start instantiating a prefab for every single one, and there's going to be literally hundreds. If I don't make it extend UnityEngine.Object, I can't get Unity to access it.
Here's my two prefab-based classes:
public class PersistedMySpecialTypeList : ScriptableObject
{
public List<PersistedMySpecialType> MySpecials;
}
[Serializable]
public class PersistedMySpecialType
{
public string foo;
}```
The image attached is as close of an attempt as I've been able to accomplish so far, and uses the inspector on the `PersistedMySpecialTypeList `
Guys I was wondering if it is possible to edit memory using unity
like Allocate Memory
Free Memory
Protect Memory
Read Memory
Write Memory
uh, what are you trying to do?
I don't think you can explicitly set memory targets, and I don't think you'd really want to anyway. Closest I could think of is you could allocate byte[] and store things in there, or allocate pointers.
Just wondering if it is possible. I just had a game idea
I don't see how a game idea would lead you to those
obviously you can allocate, read, write, and free memory.
I'm just trying to come up with different game idea
I wanna be different
What's so dangerous about that. Reading my own game memory isn't dangerous
If by Protect you mean, protect in the page protection sense, you probably could, but why?
how is Void Start() initialization if Initialization gives a variable an initial value at the point when it is created 😩😩
what??
give me sec
public class Foo {
int x = 5; // this is initialization
Foo() {
x = 10; // this is assignment in the constructor
}
}
Start() is called right before the first frame is going to be produced, so it happens even later than Awake or construction
what is the goal of setting tree?
transform.gameObject is just the current gameObject
you shouldn't need to store that
Oh so start is called before that healthis created
no
Initialization gives a variable an initial value at the point when it is created
What are you trying to do?
I'm wondering how Start is initialization
Technically setting field values in Start is assignment, but it's called initialization because in practice that's what it is
thx
Assignment gives a variable a value at some point after the variable is created.
i love u
intialization is telling the computer a variable exists:
string x;
assignment is giving that variable a value:
x = "hello";
Initialization and assignment:
string x = "hello";
My head was gonna explode
Member variable Initialization ---> Constructor --> Awake --> OnEnable --> Start --> Update
There is a reason some games use something like void Initialize() {} and set up all the variables in there
And yeah, even though it's technically assignment it's also the "game" initialization
umm make seense
but Initialization = gives a variable an initial value at the point when it is created.
right, you can think of the word "initialization" having two distinct meanings, one for the technical variable initialization and one for the game initialization
so in Start you initialize variables by assigning values to them
ow 😋 thank you so much you guys are so helpful
Think of it like English language vs programming terms, which of the two the person was trying to use is up to context
include in c++ and using in c# are they the same
Because #include copies code and paste
Does using also copy code from the file and paste it
if you can make sense of the low-level code on the right side, you will understand everything 😄
what's your objective? why do you have a data type like this?
Where can I learn low level code
I know it's like ultimately helpful
Go learn assembly
thx
do u speak assembly
like why would someone using unity, a programming environment, ever need to write "three" instead of 3?
Nope, I understand it but I don't think in assembly, I think in C# D:
in the inspector?
yeah
if someone has to do that, that someone should throw their computer away and use a loom
i'm gonna buy course for assembly
your inspector should just be the integer value 3
the user you're replying to shoudl be asking in #💻┃code-beginner
That is a challenge in https://projecteuler.net/
A website dedicated to the fascinating world of mathematics and programming
I already asked this question yesterday and I thought I understood, but I didn't... I don't know how to call the exampleFunction(); from the exampleClass without the direct reference. Currently I'm creating the moddingAPI class library (.NET Framework if this is important) so it's basically a new project without anything imported, and I don't know how to get the reference to the exampleClass. I hope you can see my problem.
your objective is to make your game moddable?
Yes sir
what kind of game is it
2D
what do you do in it i mean?
what would players mod?
i vaguely recall you received some bad advice
are there any existing players?
uh yes, they can import custom tilemaps, spritesheets, just the whole game open to them
and is this windows only? PC only?
Only PC yes
import custom tilemaps... built in unity, or externally?
windows and macOS or just windows?
so players are expected to add unity assets to your closed source binary game?
have you ever tried modding Cities Skylines?
Yes have seen their modding api too, but didn't really try to mod it
Little confused about Vsync and lowering FPS on android. Apparently you cannot turn Vsync off on Ios Android, but according to the docs, if Vsync is on then targetFrameRate is ignored. So how do I set the framerate to 30 FPS on android if I cannot turn off Vsync and targetFrameRate is ignored?
I've abstracted down the problem quite a bit because I didn't want to explain the full thing... but since you asked:
I'm using a string encoded (and very lightweight encrypted) encoding of a float that gives me lossless storage of Vector2 values, including a parity. I am storing the vector2 values, but because of the nature of float values (3.2 can have several different bytewise representations in floats), I want to be able to either write the encoded value or the raw value in my inputs.
So, to my point, the implicit operator calls my encoding to allow me to more easily handle them for file IO and for math operations without needing to make the intermediary calls to do the encode/decode every time. I'd like to be able to write the encoded OR decoded values in the inspector to edit the underlying value.
okay so i think this is probably going to be too challenging for you. have you looked at the uMod asset store asset?
you're not going to have a working thing for months, you're going to be reinventing umod
or you're going to be one of those toxic people who says they have something working when they don't
in a chatroom or whatever
i think you should use umod
oh no, I want to code my own stuff, the thing is, I already know how to approach this, but I don't know how I can call the function without the direct reference
why would you ever need to enter this weird encoding in the editor?
why don't you just edit the real vector3 in the editor, and expose the encoded version as a property?
are you trying to protect your game assets this way?
like what's the objective
i don't think the implementation matters so much since it doesn't make sense at the moment
were you talking about making a cookie clicker game a while ago or something
okay well you should download the umod asset then and at least look at how it does things
that will be the best learning for you
The objective is I'd like to be able to modify either one of the input fields for the interpretations of my underlying value, and have the other input field immediately reflect that result.
no i get it
i mean why
you're being really shy about saying why
usually that means you already know it makes no sense 🙂
The Vector2 is used as seed data for a Random, and I want consistent results.
okay well i have your answer, but you gotta tell me what you are trying to do
then i will tell it to you
it was like 30s of googling
like what's going on with this data structure, why do you need it
this doesn't really tell me anything
[CustomPropertyDrawer(typeof(CustomStruct))]
public class CustomStructDrawer : PropertyDrawer { ... }
lets you define a custom inspector view for your struct
you can make it behave however you want
i think this is a bad idea though
because your struct makes no sense
and as a rule i don't help people who are trying to do stuff that makes no sense
there's an example of a custom property drawer here: https://stackoverflow.com/questions/54748945/unity-custom-drawing-of-a-struct-in-the-inspector
you can use it to write whatever you want, however you want
if you want to immediately update the other value go ahead and do that
Because I'm trying to make Random more deterministic, and I'm using the object's point in space as its seed because then I have a single point that controls both appearance and its point, so as long as that thing is at that exact point, it'll look the exact same. I'm making a solar system simulator, and these vector2s control my initial conditions.
okay, but then you have no need for a weird struct
it isn't clear to me at all why you would need this
Flatfile storage of vector2s is inconsistent.
if you need to store something... store it?
void Save(Vector3 someVector) {
var valueToSave = CreateWeirdValue(someVector);
// write value to save??
}
i don't know, what is going on here
you can store vector2 floats by writing them, and it will be perfect
on all platforms?
of course you can store floats
what are you trying to do...
I also want these to be user-sharable, and sharing exact floating points won't guarantee the same results, and the location is an important piece of that information, this contains it all in one place.
Point is, I have two different ways of viewing the same data. You could pretend it's a Date for all I care. Humans don't really understand 1636660701295, so if you're storing that, it'd be nice to be able to edit November 11, 2011 3:58:23pm instead.
are you saying a vector2 from the editor?
if you are concerned about stuff like that, maybe use a vector2int instead?
and if you need a "floating point" value for it, you can just... divide or multiple it or whatever?
why would an end user need the unity inspector to behave a certain way?
are you trying to procedurally generate content in editor?
if you need stateful random, use XORShiftRandom, which is implemented easily
are you trying to do a behavior like the slipways world selector?
They don't, that's the point of what I'm getting at. I need this capacity, and the end user does not, otherwise I wouldn't have it in the inspector.
are you trying to procedurally generate content in editor?
Some of it, but only the initial seed conditions, and I want the seeds to be easily rebuildable.
i think you are really overthinking this
are you trying to do this?
like some string representation of the seed?
Analogous to that, yeah.
and then the user can select something on the map?
well do you think the slipways guy does something weird like a union struct
this is a unity game
what do you think is going on here? do you think you can put the mouse down in the same location and get the same seed?
is that important to your game for real, or not?
i think it's as simple as
ulong ToSeed(Vector3 worldPosition) {
Vector2Int finiteLocation = SomeArithmetic(worldPosition);
return (ulong)finiteLocation.x << 32 + finiteLocation.y;
}
is this helpful?
you're way overthinking this
then
String ToUserRepresentationOfSeed(ulong seed);
ulong ToSeed(String userRepresentation);
and seriously don't overthink it, it's just cosmetic
you never need to store the user representation
if you want to make it work in editor, do not custom property drawer a seed
you're starting to catch on to what I'm trying to do.
create an editor window that just lets you translate it
don't create a Seed struct
just make an editor window with a number field and a translate button
and another string field with a translate button
Okay, so you don't know how then. Thanks for your time anyway.
no i do, it's with the property drawer
it just doesn't make sense to have a Seed struct 😢
i showed it to you
anyway, i tried
Is there a simple way to tell if there has been any player input in the last frame?
^I have been using OnGUI but apparently you shouldn't use that
what's your objective?
with Input System and EventSystem, yes
Just do actions in responce to input
hmm
Input is dead
i can tell already you are reinventing EventSystem and Input System
based on the question
Is there a simple way I can use EventSystem to do this?
"i want to detect if the user is idle" or "i want to know if they should deselect"" or...
it depends
i want to detect if the user is idle is also what I want to do
event system doesn't do keyboard
Input System answers this question exactly, for all kinds of user inputs
my game is a card game, and everything works just with regular input, including android IOS etc, I don't want to have to re-learn a whole new thingo just to check if someone is idle
Well that's why im asking if there is a way; so the answer is no?
no 😦
.>
@fervent sage this may be helpful. I have a similar use case where I didn't want to write a massive switch block for several user inputs, I just wanted to get whichever one they pushed down.
{
int? result = null;
for(int x = 0; x < inputs.Length; x++)
{
if(GetButtonDown(inputs[x]))
{
result = x;
break;
}
}
return result;
}```
That, combined with `Input.GetAxis("Mouse X")` and `Input.GetAxis("Mouse Y")` should be able to tell you what you want to know to figure out if a user's idle.
running that each frame is gonna be intensive, my primary objective was to get a notification on user input, which this kinda defeats the purpose. Probably best just to learn the new input system for me
Thanks tho
It's actually not that bad tbh
Hmm, thinking about it, the only time I want to know if I'm idle is on android actually, and then the only inputs are touch, I can probably just check touches...
Also if you really only want any input you can do Input.anyKeyDown
or check touchcount yes
Aha! that's what I was looking for! I still would need the mouse to check tho
I think it checks for mouse clicks too
try it out
I need to check for mouse movement, but yeah I will thanks
Lastly, is there any recommendation on putting this anywhere other than Update? - I assumed OnGUI() was "when you get user input" but apparently this is not true
As long as you stay in the hundreds of things iterated per frame, you generally won't suffer a performance hit.
OnGUI is where you read Events. Input.XXX should be read in Update
Ok thanks
Thanks all of you
OnGUI is for the deprecated immediate mode UI system
i wouldn't touch it at all
uhu
I'm running a form of mazefinding algorithm for my project, and I have a performance check that runs on a 20x20 grid, 250 times. It'll handle that in <1sec on a pretty slow computer.
If you really want to run it less often, you can do this:
{
return;
}
PreviousTime = Time.realTimeSinceStartup
Asked in C# discord without much response.. Hope this isn't too off-topic.
I'm designing my handshake process for networking in my multiplayer game, but I'm not super familiar with best practices for this workflow. Anyone know what I could google or read up on to learn this? My current approach is:
- Client makes connection to server (hashcash required)
- Server adds un-authenticated connect to pool of connections, waits for client to send credentials (this is a problem currently, no TTL on the pool so malicious users could make many connections to soak resources).
- Client sends credentials to server.
- Server authenticates credentials/user/etc and either disconnects user with a reason code or adds the user to the authenticated connections data structure.
- Client begins gameplay.
But I have no idea if the above ^ is good, and don't really know what to search for to learn.
What's your threat model here? Are you expecting to be DoS'd ?
Do you prevent them from re-using the hashcash?
Potentially? I mean, I don't expect it but I'm not really sure how to prevent it. Hashcash is the DoS protection - but I don't currently disconnect un-authenticated users (since ... I'm not sure what the plan is there.. like, should I wait until the user on the client has entered their credentials before letting them connect, and immediately request credentials from the server, and disconnect them if they haven't provided them within 5-10 sec?)
I know Linux has a limited number of sockets, which could be exhausted just by having too many open connections. Windows probably has similar limits.
Yes - I believe the number of sockets is pretty big, though- hopefully not a problem early on, but I'm building the server in such a way that we can scale it horizontally if needed
But I mean, essentially right now I don't know how to .. uhm... start/submit/collect authentication points - ie, I can prompt the user for username and password as cleartext strings, but then what?
Wow just learned about HashCash now. Seems cool
(and what do I store on the server? username can be cleartext but .. password? no idea)
the direct predecessor of Bitcoin
Yeah, HashCash is 🤯 cool
private/public key would be a good way to do this. Public key encrypts, transmit to server, private key decrypts.
But.. I don't need to decrypt the password, right? In fact, I don't even want to have access to that?
One way encryption. password->Hash(password) == storedPasswordHash?
yep thjis is pretty standard -but you also want to salt it
Just using default Object.Hash? do I need to salt it or anything?
So in your DB you store this:
User:
- username
- salt
- hashedPw
And... what do I salt it with? A fixed value of some sort..?
Yes salt yes use special hashing, and make it proprietary and unique.
Sorry - these questions feel super basic
Salting can be done a number of ways. Multiply by some number, split strings, replace a character with another (careful with that one), add something to it, etc.
When the user sets the password initially, you generate a random salt, then append the salt to the password and hash it, and store that hashed password and the cleartext salt
So the salt is embedded in the client, right? client prompts user for password, client hashes & salts entered value, sends this string to the server, server stores it (at user creation) and compares it against authentication requests in the future
hm, ok
then when you receive a login you append the saved cleartext salt to the incoming password, hash it, and compare to the hashed password in the DB
server salts
always
client never sees the salt
so wait.. the client submits cleartext password to the server? (it's encrypted so that's ok, not worried about man in the middle attack)
otherwise the client would need to know the salt if they switched devices
yes the server gets the password in cleartext after decrypting TLS
If you want your client to encrypt it, I'd recommend using a secure connection protocol and let the transmission layer handle it (e.g. handled by SSL/TLS/HTTPS and not you)
There's a way to avoid sending the plaintext password at all, but it's overkill
ok, so the server hashes, salts, stores the value
It should never be logged or stored anywhere other than in memory for as long as it takes to hash it
right
The #1 rule of secure login and authentication is not to roll it yourself
Surely there must be an existing system
ok so.. high level recap:
new account: user enters password -> client encrypts packets -> client sends to server -> server decrypts password (in memory) -> server hashes, salts, stores in DB
auth request: user enters password -> client encrypts packets -> client sends to server -> server decrypts password (in memory) -> server hashes, salts, compares against stored value in DB
yeah i really don't want to do this myself, but I haven't been able to find what i'm looking for
There's existing protocols and techniques but it's inevitably somewhat bespoke to your given server application
server decrypts packets*, being slightly pedantic
right, thanks
more or less - yes. The encrypting and sending and decrypting part is generally done somewhat automatically by TLS, assuming you're using HTTPS for all of this
so I have all the encrypt/decrypt working, but now i have this plaintext password (in memory) on the server and just have to figure out how to deal with it.. i sort of didn't want to roll my own but i went down the rabbit hole of learning about EAP and MsCHAPV2 and stuff and ... just got demoralized at trying to duplicate this
In Java we used the BCrypt library for the salting/hashing
I'm using Ruffles rUDP which handles it for me.. i'd have to dig to see what it's using under the hood
is there no .NET hash/salt/etc library? I've read that I'm not supposed to use SecureString anymore, and don't really know how to develop a secure salt algorithm.. I mean, I'm sure I can google that aspect up but I'm sort of new to this uh.. space? concern? area?
Easiest way to salt would be something like string hashedAndSalted = Hash(password + "SUP3RS@LTY")
So I don't wanna fuck it up, even if it is only for a video game 🙂
Ah, right.. that makes sense.. and I suppose I could make a reasonably long salt string and just keep it somewhere safe
env variable on the server or whatever
I'd recommend not storing it in version control, use a server config and keep it in a special hard-to-reach place.
We generated a random unique salt every time the user set the password and stored it in the DB next to the hashed pw
I am vaguely aware of how to rotate them as well - ie, have two salts, a primary and a secondary, try both, rotate to the secondary every few months, then back to the primary or something, and whenever a successful login comes in on either, re-compute the other
so each password has its own salt
You probably don't want the same salt for all the PWs
that means someone could build a single rainbow table for your whole DB if it leaks
Hm, ok, that's an idea too.. so even if the algorithm is compromised, you still can't brute force
and get most of the passwords
If each PW has its own unique salt you need a whole rainbow table for each password
which is not practical
I know there's a trick used in cryptocurrencies (using a nice property of elliptic curves) to be able to send a fingerprint of secret data (e.g. a password), with a challenge-response mechanism to be able to send evidence that you have that secret data, without ever passing the secret data to the server. Is there any common usage of this pattern in password authentication systems?
I think I'm reasonably secure (said every CTO ever) - VPN access only to database, rotating primary/secondary API key for database, cloud DB (let microsoft handle all that patching nonsense), encrypted network traffic, hashcash connection challenge..
actually, hm..
Yeah this is how asymmetric encryption works, like Diffie-Hellman that TLS uses
or just public/privat key encryption
not sure which is more like what you're saying
Make sure your table/db is encrypted, too. That should also be handled by whoever manages your db.
yeah, it's cosmos db, so that's all native
well yea. I guess you could generate a private key based on the password.
ALso yes this is how those like rolling code RSA devices work. Given a timestamp and your secret key, you generate a token, the server does the same, and if they match the server knows you have the secret key
I'll have to read up on this.. do you know what this algorithm/process/tech is called?
Even if it is for a video game, you're handling data sacrosanct to the user, and should treat it with the utmost of care even if they don't. I'd even be taking similar measures to secure emails (if you collect them).
Especially considering the UK and EU's GDPR nightmare
Yeah, I will be.
Say hello to 5 million euro fines
By this point the user is an idiot if they're not using a password manager with random unique passwords, but yes this.
I think I'm more concerned about preventing cheating (vs hacking). Botting or autoclickers or what have you. I have some ideas, but .. overall it's a little daunting.
We cater to the idiot users as well as the clever ones
it's not really directly related, but the mechanism I'm thinking of is basically Hierarchical Deterministic Wallets + ECDSA
Because the idiot users may be idiots, but are still protected by law
This is actually another small problem - my approach currently requires me to handle the password directly in the client, meaning... I have to think about ways to not let a compromised device compromise the client's password inadvertently, while still allowing sign-in to be relatively painless
thanks I'll look it up
You shouldn't store the password on the client
Prompt them every time they need to login..?
the result of this whole authentication scheme should be the server sends the user back a temporary auth token.
That auth token can be used to authenticate any further requests until it expires
And it's good for x hours
yea
You may want to look into JWT/OAuth if you pursue this model.
so if that's lost, worst case scenario the attacker gets to use it for some hours, but the password is not compromised
Right - so the "password" box will show like a bunch of asterisks (if the token is still good) but never actually be editable
sure, or don't even show a login page, jump straight to the action
if you have a good token
And if the user logs in using that token, they get a free refresh .. and I suppose I could hard-invalidate it every few weeks or something
Right, even better. Awesome.
Y'all are smart people.
❤️
shoulders of giants.
I did get paid to do exactly this professionally for a few years 😛
I do want to eventually implement OAuth and SSO using other providers but ... I haven't found a library that offers this that supports windows/android/ios yet - even the Google Firebase one doesn't. I'm worried I'm going to have to roll my own here, eventually, too
what went wrong? 😆
My whole password database got compromised!
😛
I kid, I just moved onto other features
haha
PraetorBlue was Captain of his industry.... until he took an arrow to the knee
I'm actually in the middle of a mid-life-crisis, thinking about moving into game development full time. I work at a public sector job now where I'm surrounded by zombies just clocking in/out every day and ... man, I hate it. I look forward to writing code every day, more than any other job I've held in IT in the past - and I've done pretty much everything .. product management, project management, CTO/CEO, QA, customer support even.. All I want to do is fix bugs and write code.
welcome to the club
haha yep. I was on the management track for a bit. Just meetings and performance reviews and project planning all day.
Had to step down from that role and go back to IC
It's soul sucking
Hard to walk away from the benefits.. but .. yeah, I just can't stand it anymore..
Soul sucking is a phrase i've used about 600 times in the past two weeks in conversations with friends and family
Anyway, back to the code. 🙂
I'm working in game dev for a similar reason... help keeps the edge sharp. I may do some weird stuff (@undone coral ran into that), but most of the time it's to help keep me on my game.
I was trying to implement a fog of war minimap for my game, and I was almost there but Unity keeps throwing some really weird behavior on me (more info in #archived-urp channel, one of the latest posts). So, if I can't go through, I'll go around. Do you guys know of any way to implement fog of war other than using non-clearing camera, render texture and alpha-inverting shader? Any other variations or alternatives?
You mean just a minimap with a limited vision? like having a radial gradient around it?
Hello, can someone help me why the billets are going through the walls? I have rigid body ticked.
I want to stop the bullet when it hits the wall
Thank you in advance
Are you on the 2021 tech release unity version?
Does anyone know how I can implement in-app purchases that are compatible with Steam? Any video tutorials would be awesome. I can't seem to find any on Youtube
just destroy them when they hit the wall, or rather you will probably want to disable them and add them to a object pool. Alternatively you could remove bullets altogether and use rays as many shooters do.
if you mean the bullets go through the wall without a collision being detected then it means your bullets are too fast. Checking continuous collision detection might fix the problem, but it is costly, you can slow down your bullets, increase your collider sizes, or use rays on your bullets. This isn't really an advanced code problem tho..
How does the Event system handle graphic raycasters? if you have multiple canvas (and multiple graphic raycasters, which one does it uses, if any?
Situation 1 : Get the current PointerEventData, in Update(), loop through each element in the "hovered" stack and print each of their name. Result: Any element present under the mouse position is correctly placed under the hovered stack, whether it lies in the global Screenspace Canvas, Worldspace Canvas or other smaller canvases.
Situation 2 : I implemented a custom Dragging method, at the end of the Drag event, OnEndDrag() is called, in which we loop through every element of the hovered stack to find if one is a "DropZone". Result: The elements in the hovered stack don't seem to match the current situation.
The PointerEventData is updated every frame as well. Setting the "blockRaycast" parameter of the dragged object to "false" also fixes the behavior, although I don't think this should affect the hovered stack, besides the dragged object itself not appearing in the list?
There also seem to be inconsistent behaviours between the different variables of PointerEventData. If I have a main object which raycast targets are children images, pointerPress returns the parent GameObject while pointerEnter returns the targeted graphic rather than its parent, not sure where the difference may come from here. My parent object has 2 scripts, one which implements OnPointerEnter and the other OnPointerDown
As far as I know, all of them? Input modules will generally just call EventSystem.RaycastAll(), which casts against all registered BaseRaycasters then sorts the results.
DontDestroyOnLoad
Actually I need it to be a bit more complex. I have a minimap as a static UI image, and an overlay on it. I procedurally create a field of view mesh which is then rendered with a separate camera with alpha = 0 background and then inverted by a shader and projected into the overlay, so as the player moves around, his field of view is projected as alpha = 0 within the overlay, which reveals the underlying map. All that is working now. However, I'd like to keep the already uncovered/explored areas in the overlay. For that I wanted to use Don't Clear flag. Trouble is - it doesn't work consistently (which I assume to be a bug), so I was looking for some ways to bypass this issue. If you look at the videos I posted in #archived-urp, you can see how the feature looks like
Oh okay thanks, sadly that doesn't answer my biggest issues but damn, Unity's system is wonky
Imo even projectile bullets should be made by raycasting step by step every frame. Raycast method should be pretty cheap assuming theres no hundrets of bullets flying same time.
One method is to raycast every frame, find the distance, and if the distance is inferior to the travel speed of the bullet, act accordingly
It use the first one it hits, starting from the one with higher sort order
So, if the raycast hit a raycasttarget inside the top canvas, it will stop there, else, it will continue to check any raycasttarget in another canvas below.
The PointerEventData is updated every frame as well. Setting the "blockRaycast" parameter of the dragged object to "false" also fixes the behavior, although I don't think this should affect the hovered stack, besides the dragged object itself not appearing in the list?
that's because the dragged object always get detected as it follow the mouse position, which is where the raycast is cast. Your solution to set the parameter blockraycast (or raycastTarget?) seems like the simplest/best solution to me
I get that, but shouldn't the hover stack also contain everything that lies under the card?
Wait, hover stack?
PointerEventData.hovered
yeah I've just googled that 😅 I've never used it actually
I think that hovered stack is a result of something like raycastall while eventsystem.currentSelectedGameObject is from raycast
I'd think so as well but the results are kinda inconsistent
Or maybe it doesn't work like raycastall at all, instead it add gameobjects which getting hovered and remove those getting unhovered, that's why your dragged object doesnt appear in the list since it's already hovered...
My memory is a bit blurry, but I kind of bumped into this kind of inconsistent issue a few years a go
@somber tendon yeah, seem like the kind of thing where more documentation could be helpful, but I found a workaround for now so it should be fine
Thanks for the help
No problem 🙂
Yeah, lately documentation seems to be getting vague in some place
well you can just set the max distance of raycast to match the amount you need to move according to speed. if we don't hit, then start the next ray (next frame) from the position where last ray ended.
Guys I've been trying to get flying pathfinding to work but the results are not so great, unity's navmesh agent just isn't doesn't work for flying and I tried coding my own system and although it flew perfectly and followed the player it just completely sucks at avoiding obstacles so I literally have no idea where to go from here
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://preprod-temblorapis.lecode.games/api/auth/LoadGame?day_name=3&game_play_id=9. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)." I am getting this error in build for some calls and for some I getting success response, Any suggestions or solutions.
Please help, tried everything to fix it - Releasing render texture that is set as Camera.targetTexture! Context : Android, using custom render texture (asset) in the addressable prefab. When releasing gameobject via addressable release instance - it always throws this error. What should I do?
Pure question out of curiosity, if i register a local function into an event inside a function does that bring any memory leak into play?
void Something()
{
void DoOtherStuff()
{
myCoolEvent -= DoOtherStuff;
}
myCoolEvent += DoOtherStuff;
}```
or even simple anonymous methods through a local variable (not sure if thats the right term actually)
This allocates to heap memory, but it's not a memory leak because it will always be garbage collected eventually.
when i started working with c# i read a golden rule
"please be nice to the garbage collector"
so how does that play into this?
on one hand, you are absolutely right
on the other one this puts load into the garbage collector right?
(sorry if i say something wrong, trying to make sure i get this right)
Sure, delegates are objects and myCoolEvent += DoOtherStuff; is shorthand for myCoolEvent += new Action(DoOtherStuff); (assuming myCoolEvent is defined as an Action), so you're creating a new object which will eventually have to be garbage collected.
Every call to Something() instantiates a new hidden object to store the local state
And you can get stutters from the garbage collector if there's a lot of garbage to collect in that particular moment, but Unity's new incremental garbage collector reduces those stutters.
mhm
Only if there is any state to store. In this case, there's no local variables in the method so it doesn't capture anything.
yes, true.
There's potentially two allocations. Any captured variables will be stored in one class, and the event record itself is another.
Okay, im sorry where can i began to study these again, it seems like i completely skipped that part when i was learning how to work with c#, and while i have some general knowledge on stuff, i wanna know more about garbage collector and its heap, i know about its states per example (0 - 1 - 2 etc) but not any other stuff and how it micro manages
thanks for the sharplab link
There are extensions for most IDEs for showing heap allocations in C# code as warnings, like:
Visual Studio: https://marketplace.visualstudio.com/items?itemName=MukulSabharwal.ClrHeapAllocationAnalyzer
Rider: https://plugins.jetbrains.com/plugin/9223-heap-allocations-viewer
thank you!
can any one help me here with custom assemblies? I am having a problem
cant find do fix
everything is working good but If i bulild the game I get this
that script is a editor scrip
dont know if this is the best place to ask for help in here
ok I found out that the editor scripts dont compile
they are only for editor use, had to place the scrip in a folder in assets/editor
no
the most consequential memory leaks will come from rendering effects you try to author yourself, like using render textures.
you shouldn't really worry about allocations or memory leaks or whatever in routine c# code
they might be real, but they don't matter
Hmm, I need to read into the garbage collector to bear a proper judgement
that's just my #archived-code-advanced perspective
The issue while this generally isn't an issue I believe smaller end targets will be affected more probably
But I am not sure!
I'll read and I'll know
what low end target?
An old spec system per example thats what I meant
yeah, but name the specs
I don't have anything specific in mind, let's use as an example 4th Gen Intel cores
that idea of the low spec system... it doesn't exist in reality anymore. besides, are those people going to try new games?
why would someone on a 4th gen intel try a new game?
how many new games do they have in their steam library?
we can answer this question. they're already exceedingly rare
Hm, you are right maybe its a smaller demographic than what I overthink in my head
it's not just a smaller demographic, you will not meet personally a single living human being in your life with a 4th gen intel CPU who also tries new things
i understand they may play games
but they don't play new games, like yours
this is just #archived-code-advanced
(my girlfriend had a 2nd gen cpu with a 1050 ti and game and tried new games)
#archived-code-general : "blah blah blah garbage collection"
yes, but what was the last new game she tried?
Don't get me wrong, I'm just a skeptic atm
horizon zero dawn was released 4 years ago
like what are we even talking about
anyway
i think this is a good point well made
4 years ago!
so you have to not worry about people with low specs, pretty much ever
for a game that has 0 users, the low spec audience is irrelevant
tomb raider is 3 years old
these aren't new games
there are many good indie titles that run on low spec machines on steam that are less than a year old
it's just that, people with low spec machines also happen to be people who will not try something new in every sense of the word
usually this comes up in targeting android users, which i think is a colossal waste of time
because android users don't try new things, so why bother making your game for them
worse phones, way smaller budgets, don't try new stuff = a disaster audience
My experience with Android is my equivalent of whichever experience anyone had with lisp
So I'll take your word for it for noe
Now
lol are you trying to say, horrible?
Non existent is more accurate in terms of developing
Ok I hear your points and i think you make sense for the most part
what is going on here
why are you using a render texture to implement a blur?
To begin with a good demographic will have to upgrade to newer systems due to windows 11 requirements
well it's more that, if you look at people on steamdb.info with +$1,000 accounts
who have indie games in their libraries
that could run on potatoes
they try a lot of new things
they have very fancy computers
they just care more
Oh steamdb.info is an excellent suggestion for comparisons right
they have more money, so they buy nicer computers and spend more on games
same with the ios audience
your antagonist is poverty
Yea I'll be honest that I was ever so slightly biased due to my country (Greece) and 7/10 people I know have crappy systems
But I had to think globally
don't use multiple canvases, don't make a custom drag
what is your objective?
it's tough. the best platform in Greece is going to be iOS
because people have iphones, and iphones are nice
I have met 4 people with iOS in my whole life
We make 800 per month on minimums wage and iOS costs like 1500 ish
what you can target for people who try new things
it might be something like the nintendo switch
Nono I don't target Greece as my target, I am merely explaining what Initially had in mind
How is that advice?
But thanks for the help and answers
i agree that the OnDrag stuff is really bad
but eventsystem doesn't practically work with multiple screen-space canvases
are you making a card game?
Screen space canvasses (and unity UI in general) works horribly, it has a learning curve that's basically the key of sol in music, atleast when you want complex functionality
Unless they created a better solution for custom rendering order, that's not gonna be possible
what's the game though?
There is a custom rendering order
^true
The key of sol?
are you trying to make a webgl game? it's telling you what the issue is. you can't run a webgl thing on "localhost" and then have it access "prepod...lecode.games"
Does anyone know the Steamworks API call to see if the user is on a Steam Deck?
that's right, it doesn't work for flying
you can search google for 3d pathfinding unity
you can fake it by raising your object to a certain height
3d pathfinding is easily made now with the new custom unity navmesh
Fuck I'm on the road and can't fetch links
Plus if you want an accurate algorithm I suggest you look into A* as it's the most optimal algorithm for such things
Especially since Euclidian distances are easily made here with just the distance between agent and target/goal
@glacial geode afaik, there is one in Canvas
what are you trying to drag and drop?
@glacial geode I've never heard it called a key of Sol tho, I think the correct english name would be Treble clef?
like a card into a spot?
Irrelevant to the topic but the English name is sol key
They're both correct, funny that they translated it directly from the french, must confuse quite a lot of people not knowing that Sol is G
I doubt that's relevant
It is cause we can give suggestions on ui structure
You can give an abstract example
i'm just worried if you can't describe your game in a sentence, it just helps visualize what your issue is easily
^
it would help a lot
I can, I just don't see the point
Imagine this and I'm speaking from experience
On one hand we can give you directly a quick answer and you go your merry wY
At least not to answer the question of whether there is something that canvas that allows for custom sorting orders
Way
Buut
If you can explain it and something is off we can help you design stuff even in the future with an ease of mind
It's just a way to also verify ones sanity
It helps establish the order and if something can be done in an easier manner
I can go on for days
for example, to make a drag interaction, it's easiest with unirx, and the following bakes in a lot of knowledge:
class Draggable : UIBehaviour {
void Start() {
PointerEventData pointer = null;
this.OnBeginDragAsObservable()
.Subscribe(newPointer => {
pointer = newPointer;
}).AddTo(this);
this.OnDragAsObservable().Subscribe().AddTo(this);
this.OnEndDragAsObservable().Subscribe().AddTo(this);
Observable.EveryUpdate()
.Where(_ => pointer != null)
.Subscribe(_ => {
// check if the pointer is still pressed.
// if not, set it to null.
...
// get the hover stack or raycast here. now it will work.
...
// set the transform movement
...
}).AddTo(this);
...
okay well, this will be the last chance to help you, but hopefully you can just briefly describe what it is you're trying to do
believe it or not the pointer event is mutated
in event system
it's ideal to use new input system instead of classic input
the approach i wrote also works for stuff like multitouch
and deals with taking things off screen, which happens frequently in the editor or windowed games
Doctor I can't check but remind me can sorting layer be applied ?
I did check briefly but can't read details on the road
Also how come you are using this in your code? Is it needed when by default a definition in c# refers to the object running?
It's not like we are messing with class constructors or getters and setters
it has something to do with UniRx's extension methods
it's something idiosyncratic to it
Ah right you did mention unirx mb
canvases allow you to set a sort order, you can have a "child" canvas
but... the best way to do a sort order is using the hierarchy
you already have sort order in UGUI, it's just the hierarchy
it just means the user is going about something wrong
and if only @mighty latch would tell me what he's trying to do
i would help him
Yea 9/10 it's easier to use just the hierarchy
it's going to be a really common fix
like having a dummy object that is what you drag
and the visual object is constrainted to it
yeah
That is a copy of the previous slot
that's such a common pattern
With a bit tweak
so i really want to know what's going on 🙂
Yea I also agree that the vague secrecy ain't helping
An abstract example is easy to do
It's not like he is disclosing company info or whatever he is working on by using examples or generalisations
That's what I've been doing for 4 years atleast @mighty latch
If it's any consolation atleast I mean
I'm currently making a Paper Mario style game and one big part of the battle system are the action commands, in which you need to time your inputs at the right time to do an successful action (see the normal jump here for example: https://imgur.com/a/cXOSJLw).
How would I approach implement this timing based input?
Just need to know where to start.
Also, would you go the timing by frames or by "real" time?
you can sequence the combat with Unity Timeline, and add markers (https://blog.unity.com/technology/how-to-use-timeline-signals) or intervals made of two markersto denote when and which buttons should be pressed
That's exactly what I was looking for. Thanks!
Guys, i stopped unsing unity in about 1 year, and i decided to come back. I was using Photon2 for multiplayer, but it was laggy and it was player side server. What are other options that i can use? Anytning new?
I sa a video of Crab Game and he used steam. Is steam a good option??
If you want to pay $100
use unity mlapi. it's the new multiplayer framework native to unity
Just fyi it has been renamed from MLAPI to "Netcode for GameObjects"
yeah i saw that......i liked mlapi better.....although people more often consufed it with machine learning. so yeah, i get the namechange
Ah, yeah I can see that happening. I personally disliked it a bit because it was more the name of the 'type' of API than a 'product' name. However I don't really like the new name either because it is to 'descriptive'.
is it good?
definitely
Is player server side, or can i place all the lobbys in my own server?
it should support user servers and dedicated servers
Nice! Thanks for the info
Might make a bit more sense when you consider that the DOTS networking solution is called netcode
Not any more it's not. It is now "Netcode for DOTS"
I imagine the goal was to reduce confusion within Unity products
I mean, I get it and it makes sense, I just don't like how it sounds 😛
Yea the branding isn't very catchy 😄
Question, is it true that doing even P2P multiplayer is 1.5x as much work as single player?
There's #🎥┃cinemachine if it's something very specific to CM
1.5 is a very optimistic number
Not surprising, I think 1.5 is the number I saw a number of years ago when I looked in to what multiplayer entailed. Thanks.
There are a lot of variables to that, like how what frameworks you are/aren't using and what kind of quality you are aiming for.
since we're on the topic of multiplayer right now: what's up with SpatialOS? i've still got a legacy account but appearantly it got moved to be a part of zeuz? i can't find any SDK though
I'd estimate.. 3x.
Let's say I want to detect entities within a certain range of my gameObject every frame, what would be the most efficient way between a trigger collider and Physics.OverlapSphere?
Hi! I need to make my own Input library in order to have a frame independent Input
Do you have any kind of tutorial to get started with something like that?
Dunno where to start tbh
New input system should be decent
no you don't. just ensure your code performs well enough that it can work with a high frame rate. (Unity can go well up to 250fps)
I don't need something decent
I wanna learn to make my library so it is great
It's a rhythm game so I have to be as accurate as I can
Did you check lower level input system stuff?
Yea I know, it's supposed to be good now
I know people who used native input plugins in the past but have no issues with the new input system
Many people who worked on games of the same type told me they use native input plugins
So, how can I make that?🤔
yes I do, it's a rhythm game I need accuracy and calling it once a frame isnt enough
sadly
this is an imagined problem unless you actually have demonstrated it
at a frame rate of 250fps, the delay between frames is 4ms. The perceptual accuracy of humans (when it comes to musical beats) is much larger than that
it may be possible that they dont really operate on perception
have you seen the people that play guitar hero/ddr and the like?
their neural networks have the songs and keypresses integrated on spine level
who plays at 250ms on console? lmao
its not an imagined problem, pressing once a frame is not enough for a player with quick reactions in rhythm games
your making a console game?
im thinking about the user experience
PC, console and mobile
you could build your program, and if it really is too laggy with frame-input, THEN build your own input module
its not imagined since every man I know who worked on a rhythm game has faced that same issue
Worth considering what building a native input module means in practice when you are shipping to 6+ platforms
otherwise I wouldn't be asking 😭
one of the ways people procrastinate on a project is by worrying about problems at step 50 or 60 while they still haven't completed step 2
yeah...
They did face it until new input system came out 😛
new input system doesn't works for that
It looks like you can increase the polling frequency of the input system independently of the framerate
new input system was designed to be faster and more efficient than the old one.
Looking a bit into the new input system docs, and it seems to be receiving events directly from the native input, so it should be frame independent.
I would suggest actually looking into the existing lower level parts of the input system
not enough since it has a lot of input lag and you can only know when the button has been pressed
It can save a lot of time compared to learning the system APIs for input for 6 different platforms
but not how long since you pressed it
I think flynn is just fishing for an excuse to not build his game
Didn't someone mention that there are timestamps?
what?
man I'm just asking a question
I think you can know the exact time of the event
you're asking a question but you're ignoring all the good answers, and you just keep insisting on your imagined premise
you haven't actually tried to make the new input system work for your game. You probably haven't even built your game yet. You're just assuming it won't work
man what I'm saying is that I already tried all of that, I'm thankful for the help
but I would want to know how to make my own library at least for PC now
plus, you assume I didn't started with my game out of nowhere, I just asking something nicely 😭
there's no need to be rude
I think you're kinda misunderstanding due to a lack of experience. Even if you're gonna write your own thing it's gonna be something very similar to what the new input system does.
And most likely, a team of professionals can do it better than you.
dont take personally
Maybe, but most of people who worked on big rhythm projects for Unity said to me it was normal to have those issues since the Unity Input System (old and new) are not efficient for that kind of games
Obviously
But learning to make my own library is also a way to learn and practising I'll eventually know what's better for my game
It gives me a lot of experience and in every jon they'll appreciate it
However, if people can teach me something about the New Input System I won't be rude either since I can listen to people
Well I would like to hear your results of the suggestions
Well, I don't have much experience with the new input system, but a quick look at the docs makes me think that there's no "better"/"less lag" way to get input. try looking at it yourself.🤷♂️
They even have a diagram demonstrating the architecture
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.2/manual/Architecture.html
Did changing the polling rate do nothing?
I'll take a look into it!
Make sure to try to hook into low level events and not the action system
In either case I don't think that you would be able to get a "direct" callback when a certain input is triggered, because of how OS handles input(if I get it right). The right way would probably be to know the exact time of the event and design your code around that.
And the new input system seems to provide that data.
I'll tell you, since I think it may be an interesting subject after all
I will re-try everything and even try new things
Your suggestions may be able to help me out (I hope so)
Thank you anyway, you're so nice guys
doesnt rewired have its own input polling?
As for your own plugins, you'll probably need to write some c++. And not the most basic one too.
Huh anyway, do you have any tutorial to get started with libraries? I'm just curious at this point
😭😭😭
It's frame dependant AFAIK
probably start from reading this:
https://docs.unity3d.com/Manual/NativePlugins.html
https://docs.unity3d.com/Manual/NativePluginInterface.html
Then you'd need to hook your c# code to an event from the c++ side..?🤔
That's as much as I cant tell without actually researching into the topic.
I imagine that for that to work with android, you'd need to write a similar plugin in Java(?)
And other native languages of different platforms
Hey you jumped over Mac and Linux 😛
Yea I imagine both would be C++
The api would be different of course
I'm not even sure about Mac/ IOS... I remember IOS was based on a language with a funny name, but don't remember exactly...
Oh, Objective-C is C based🤔
Always thought IOS programming is from another planet, but I guess it's not that different.
I have a crash I'm in the middle of trying to track down, but which I suspect may be related to IL2CPP + burst/Unity.Collections in some way.
In my player.log right at the top I get 2 of the following warnings:
The method `Int32 Try(IntPtr, Block ByRef)` must have `MonoPInvokeCallback` attribute to be compatible with IL2CPP!
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
Unity.Burst.BurstCompiler:CompileUnsafeStaticMethod(RuntimeMethodHandle)
Unity.Collections.Try_00000C2D$BurstDirectCall:GetFunctionPointer()
Unity.Collections.Try_00000C2D$BurstDirectCall:Constructor()
(and the same for 00000C23)
Under certain conditions (I'm still trying to nail down), I get a crash to desktop in a build - I will make a mono build and see if it happens there and also test in the editor to see if I can replicate it, but in the meantime I wanted to check if it's perhaps a version issue that someone here knows about specifically: I'm using:
2020.3.19f1
Collections 0.15.0-preview.21
Burst 1.5.6 (also got the same on 1.5.4)
(here's the player.log minus some unrelated debug.logs in the middle: https://gdl.space/vufusumica.js)
for android, you can import the cpp project to android studio project and write a wrapper class to interface the functions
Hello, I have an issue with optimisation, I have sprite skin component that's very slow and I don't know why. I'm using the 2D animation package for skeletal animation which I guess I'm not using right
Is the New Input System really frame independant or is it in FixedUpdate?
The backend polls some devices at the set polling frequency and some devices have events fed realtime from the OS afaik.
Not exactly sure what options you have for consuming that data
Is there any specific channel for questions about Unity's Particle System, a great particle system
Which devices use realtime?
Like, is there any set list or smth like that?
what is realtime supposed to mean in this context? Everything is polled if you look deeply enough
USB is based on polling devices
Realtime in the context of the input system backend. It doesn't necessarily mean that the input comes in any faster depending on the rest of the input chain.
And all of these details can and probably will change based on the platform and device type
realtime means "input will arrive no later than X after it was performed" i.e. after the original switch in the device that turned a 0 into a 1 was triggered", this guarantee DOES NOT mean that X will be a low number.
I understand
thanks
you can also manually update the input system if you like, maybe from a custom thread or custom player loop
options are Update/FixedUpdate/Manual
but if I put a high polling frequency it would be frame independent, right?
not sure how I need to update it tho
it can run faster than update but not faster than your CPU can handle
if I put Update it means it reads Input at polling frequency but it reads it after a frame or what does it mean?
enough
if it is optimized I don't think it would be such a big deal
it reads all input events and aggregates them (somehow), but updates you ingame events only once per update
ok, it reads it when you press it and it updates in the game after a frame
amirite?
not sure if I understand correctly
when you update manually, those aggregations happen each time you trigger that update, and you have to deal with the async between that and the default player loop yourself
there's not really a player loop, it depends of what you mean by PlayerLoop
its like the problem when you query input events in FixedUpdate but get none because they are out of sync
there is always a player loop
its what calls Update() and LateUpdate() and BeforeRender() etc.
When you have structural and process problems, can't figure out a way forward to achieve goals, how do your break it down: pen and paper, drawing app, word, diagrams? Just start and try to get through chunk by chunk?
Just start and try to get through chunk by chunk
thats the worst approach ever and mostly you'll waste your time when you face a new problem which you never thought of, and then end up repeating the same.
other than that, anything else works. pen-paper/drawing/diagrams/flow chart/etc etc. for me, i used to write down the logic sequentially. and then write down all edge cases and their possible solutions.. with time you'll eventually do it all mentally
I've been doing it mentally for a few years, but recently hit a snag, and need to figure a way to map out the problems and flows and edge cases and thoroughly design the structure, as I'm not capable of holding or perhaps even building the entire model in my mind.
thats the worst approach ever and mostly you'll waste your time
story of my life 😦
I try to break the problem down into more and more granular steps. My very first method may look like
{
return new Sandwich()
}
And then I break down those steps into steps:
{
Sandwich result = new Sandwich();
result.TopBread = AddBread(customer);
result.Filling = GetFilling(customer);
result.BottomBread = AddBread(customer):
return result
}```
And eventually you're describing the most granular steps of what you're trying to do.
Thank you! Needed this to jolt my brain back to being sensible. Very grateful!
"How do you eat an elephant? One bite at a time."
invite all your friends
I'm doing more like : How do you prepare a buffet and make sure everything is ready, hot and served at the exact same time? Fish, veggies, steaks, salads, etc. And have always kind of choked on the one-bit-at-a-time because there's so much that's gotta be done somewhat concurrently, and interdependently, with limited hotplates, ovens etc.
But the sandwhich metaphor, therefore, and two stage breakdown, a big reset help. CHEERS!
when instantiating a gameobject containing some TMP assets the TMP doesn't render until I go into the inspector and manually change the text from "Test" to "test1" for example. Would anyone know why? It's a really weird bug. Really struggling on this and no amount of internet searches brought up a solution.
Guys, I'm making a card game and I'd like to implement networking, but I'm unsure as to which library to use for that.. Any suggestions?
I'd mostly use it for player authentication, storing some data (such as player decks) and making 1v1 matches, so I don't need anything too powerful, but ease of use is important to me
IIRC UnityEngine has a native networking library, probably your best bet.
Yeah, I think it's called netcode, but I've also read some good stuff about a lib called Mirror, so I thought maybe someone here had some tips on which to use
Mirror does seem more focused on MMOs though
Oh, I just realized there's a networking channel, I'll go ask there
I was wondering where I should start with an AI that moves around a map trying to kill a player?
I'm about to try some fancy c# that interacts with unity. Wish me luck....
Thanks
Not trying to be sarcastic, but that's probably your best bet. You may also want to learn more about Unity's navmesh system.
Ok. Thanks very much.
lol
Since Unity is having trouble encoding objects as both json and as AssetDatabase Objects, I'm trying to create a template class to be able to save things in the AssetDatabase so I don't need to extend every single one with : ScriptableObject
Here's my template class:
public class ScriptablePersistedObject : ScriptableObject
{
[SerializeField]
private object payload;
public T GetPayload<T>()
{
return (T)payload;
}
public void SetPayload(object payload)
{
this.payload = payload;
}
}```
When I save this, the object does end up appearing in my assets, but the inspector as well as the `.asset` file show no actual data in the payload. Does anyone know of a way to get `[Serializable]` to work with template classes, or is this a little beyond the capacity of Unity's serializer?
Does anyone know if you can write into Downloads folder on iOS?
What type of data are you trying to serialize? And why would you want to do that with many individual scriptable objects?
It's persistent data related to my project, there's both user-generated data and prebaked (primitives, or containers of primitives), and I'd like to be able to store in both json and unity-serialized format without thinking about it.
Well, if you use a better json serializer like NewtonSoft's you should have no trouble serializing serializable things.
As for the asset database, [SerailzeReference] is a thing, but what you're doing kinda smells like it could be done a better way. I've never had to serialise anything like this before
what you're doing kinda smells like it could be done a better way
I'm sure... the intent is to be able to have a human-readable version of the user saved data so they can view it on demand, as well as have it generate in-engine.
I'd also like some premade versions, and those I'd like to be saved in the engine, and since they're there, I might as well be able to edit them through the inspector.
thats because if your object isnt serializable then unity wont be able to save it
If you mark the field with SerializeReference, and the data you put in it follows the serialization rules it should work
It can only save objects as assets that extend scriptableobject.
Not any object. Only the ones which are serializable
Hi. Im trying to implement a floating origin and I have a problem with light probes. I dont know how to move them via script. I've only come up with overriding anchor on meshrenderer but if I have to override a transform for a couple hundreds GO it will be very slow. Any ideas? :3
The fast way to move a whole bunch of gameobjects at once is to have them all under a single root object, and move that.
Does anyone know how SceneManager.activeSceneChanged work? Cuz I don't, not even after reading the documentation
Yeah I know that trick, but unfortunately light probe group still stay there where it was :/
And I need to compensate it for baked light, or move light probe group somehow
anyone know why The Lerp's would have inconsistent speed in this code?
oh, game objects marked static won't move correctly
and baked lighting will probably malfunction, hm
yeah thats a big problem, haha
did u try multiplying the spee dby Time.deltaTime (or any of the variations)
:|
Just to check, what's the reason for moving the origin?
I have artifacts over 1000 m from the origin, and Im making a game on VR so it's even more noticeable :/
Hm. The usual way of dealing with that is to break your game into separate Scenes, and load a new scene in when your player gets far away enough from the origin
If you've ever played Half-life: Alyx, it does that quite noticeably, with checkpoints that take several seconds to load up
Yeah That will work if I won't try to make open world, hahah
ah
I've even found a function to overcome static batching "StaticBatchingUtility", honestly didn't test if it's working but as i read the description it should :3
I don't see how that is relevant
I think i can write custom shader that compensate the origin shift
@vivid prairie You could try loading your world in chunks, and have each chunk load and unload as it gets closer to the player. The way I would get that to work well without crazy floating point issues would be to make your player always at 0,0 and essentially invert movement, either that or use some clever partitions to snap your player back to the other "edge" of the chunk when they reach the edge and re-center.
you'd have to replace all shaders you use. And it depends on what artifacts you're seeing. The physics calculations will also suffer.
It looks like the each vertex move <1mm every direction
are you generating the world on the fly, or is the entire level in your scene already?
The entire level is on the scene
how far out does it go?
I would like to have at least 4x4 km world
Are you using any LoD meshes?
I'm trying to implement hlod
is this thing going to be multiplayer?
no
is interpolateTime correctly going from 0 to 1?
well, I don't know what to suggest. By the time you get to 4096m, the resolution of float is down to 2048 slices per meter. Which I imagine is going to feel terrible in VR. What you really need is double-precision coordinates for this kind of thing.
I imagine this is the issue. If you got within a distance of the next lerp that was beneath your check, and then it looped because of a longish frametime it would reset
If you do shift origin, you may need to give up baked lighting, reflections, and such. But maybe keep asking.
have any examples for a good replacement?
You should just loop with an if statement and handle the logic of switching targets in it. Instead of trying to generalise it into one line.
got it
One solution the Kerbal Space Program uses is to centralise the camera at the origin, and rotate the world around it. The limited float space of our “world” is used purely for rendering, and the actual coordinates of objects in the world are stored elsewhere in a better - custom - system, and translated into world space on every frame.
KSP also uses the scaled skybox solution to represent distant celestial bodies. As the player gets closer to these objects they're hidden in the skybox and a realistically sized version is added in the player space which they can interact with.
Yes, but I want to keep my baked lighting and thats a problem
What's the benefit of keeping your baked lighting?
better visuals
Note that Unity's representation of the level uses the same 32-bit floats, so you've already lost precision in the description of the level far away from the origin
Okay... and do you really need the precision of baked lighting at >1mi away?
Shifting it back to the origin won't fix any errors caused by that. Including errors in the light baking.
er wait, that might not be true if Unity uses relative coordinates for the bake
nevermind
The problem is that the mesh is vibrating, I think the <1mm error for light baking will be fine
I think I'd break the world into chunks, pre-bake lighting on those chunks, and then swap out non-baked chunks and baked chunks as the chunks enter the player's perimeter. As for making sure things still look pretty all the time, lots and lots of LOD tuning and level design will help
I think we get off topic 😄 the main problem was to move baked light probes
But you can't move light probes in baked lighting...that's kinda the point. 😐
im back to sqaure 1, nothing seemed to help
I might juust have to rewrite the code but I really dont want to do that
my first time working with lerps and its super frusterating
Hey guys. I am attempting to transition some AStar code over to unity jobs. Everything is going swimmingly except this part. Tilemap is clearly something I cannot store inside a job so how do I get the hasTile check to work inside? is there a way to have it call an external function?
Can you store the HasTile info ahead of time (in a 2d bool[,] array), and pass that to the job?
@severe grove transfer the tile from 2d/3d array to 1d array and use it
that is the only way to have 2d array in job&burst
So I need 2 jobs then. 1 to construct the node array. Then I check the nodes. then send it back to a new job to finish?
no you have to store the data as 1d nativearray and use it directly
your first job won't able to read 2d array as well
navigationmap.HasTile is just using the unity Tilemap
nodeArray is already a 1d array
if u have to use job/burst you have to store the .hastile in your node when everything changed
That is what CalculateIndex does.
and tilemap is a class i guess
use a class in job/burst is not possible
hosting your own database is easy, if you know how to host your own database 🙂
I don't know what you already know, or your capacity for learning.
Theoretically it's as simple as logging into AWS and spinning up an RDS instance (or a similar competing service)
So I didn't know if this falled in advance code but I'm trying to fix a bug i'm having between the Force impulse 2D and getting it to dead stop while jumping on a climbable surface.
Basically my Jump uses force2D with Vector 2 0, Jump speed (Witch is chosen threw the editor fallowed by Force.Impulse.
When the player hits the ladder they shoot up with out any input from the player then threw another bug has the player slide down it again with no input from player.
You could check if player is colliding with a ladder when jumping, there is a method IsColliding
Tried a else statement in the jump script so far nothing
Is there any 3rd party program that you know that could pack all Unity data and exes into one real standalone exe file?
Maybe inno setup?
With that you can make installer file that you can then use to install the game
Brackeys have nice video about it
Late reply but what I want isn’t an installer
Just a single .exe file
I believe you can with an external solution
but I don't know any software that will do it for you
that is not possible
I might just be thinking of an installer though
I mean I plan to release the game via Steam or Microsoft Store
So no need for an installer
I maybe thought it would be self contained
Like in OSX
apps in OSX/macOS aren't self contained. .app is just a special package format that macOS treats in a particular way... kinda like an archive with a pointer to a specific file that gets executed when you double click... like an alias in the StartMenu.
If you plan to release it there, there should be no problem with just leaving it as is
it just looks like that
If you look in any "Made with Unity" Steam game's install folder you'll see all the usual suspects
Hello, i'm having trouble with understanding closest point to plane,
public static void DebugMouseCastToWall(float dist=5f) {
Handles.color = Color.green;
var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
var tr = SceneView.currentDrawingSceneView.camera.transform;
var wallpos = tr.position + tr.forward * dist;
var plane = new Plane(-tr.forward,wallpos);
var closest = plane.ClosestPointOnPlane(ray.origin);
Handles.RectangleHandleCap(0, wallpos, Quaternion.LookRotation(-tr.forward,tr.up), 1f, EventType.Repaint);
Handles.DrawDottedLine(ray.origin,closest,1f);
Handles.color = Color.red;
Handles.SphereHandleCap(0, closest, Quaternion.identity, 0.1f, EventType.Repaint);
Handles.color = Color.white;
}
expected behavior of this debug : a line will drawn from mouse position to the closest point on the plane which is 5m away from scene view camera.
output when i test it : the mouse position is correct, but the closest point always in the middle of the screen.
yellow is the mouse pos, red is the closest point
that mouse-ray starts at (camera position / screen center) with direction to that mouse pos., closest point to a plane perpendicular to the view-fwd-vector when viewed from a camera with that view-fwd is the view center.
a plane also has infinite size, so...
what you maybe want is ```cs
var isHit = plane.Raycast(ray, out float atDistance);
closest = ray.GetPoint(atDistance);
thanks Anikki, i changed the code to this
public static Vector3 MouseCastToWall(float dist = 5f) {
var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
var tr = SceneView.currentDrawingSceneView.camera.transform;
var wallpos = tr.position + tr.forward * dist;
wall.SetNormalAndPosition(-tr.forward, wallpos);
float hit;
wall.Raycast(ray, out hit);
var closest = ray.GetPoint(hit);
return closest;
}
and it works! i still don't understand much, must review again
in theory a raycast like this and Plane.ClosestPointOnPlane must yield same result 🤔 . but my 2 code block say otherwise...
hello i was wondering how i could make it so when i look at a cube or anything with a certant tag i can press f and it launches me in the direction im looking in. (wich is the cube>??
@simple thunder Don't cross post, and there's nothing advanced about it.
ok
https://stackoverflow.com/questions/69934430/making-a-moddingapi-for-my-unity-game-and-call-functions-without-direct-referenc If someone has a solution for my question, I would really appreciate it.
I use await to call functions with a delay using generics, but I noticed the thread/async task still runs when I stop play mode, which causes a MissingReferenceException
public async void Delay<T>(Action<T> delayedMethod, int delay, T value)
{
await Task.Delay(delay);
delayedMethod(value);
}```
Is there a way to stop all tasks when stopping the game/exiting playmode?
How can I cheaply set default values to an array of a struct
So i want my Struct.Int property to be -1
instead of 0
when i create a new list
but without it being expensive
cuz the array is large
Initialize the Struct.Int property as -1 in the struct declaration directly.
public int Int { get; set; } = -1;
You say array and then you say Struct.Int 🤔
They have a struct array (or list, both terms are employed here, but I'll go with array since fixed size of default values etc.).
Initializing it fills it with default(T), so all default values of the struct. They want a member of this struct to not be the default (0) for default(T).
That's how I understood it
ooh my bad. When I first read it, I read it as they had an array inside a struct
so basically i create a new empty struct array
and i want all the values of the struct.int to be -1
without looping through the full array
Assets\Scripts\TerrainGenerator.cs(33,24): error CS0573: 'TerrainGenerator.Vertex': cannot have instance property or field initializers in structs
i still get this error
struct Vertex
{
public Vector3 Position;
public int Index { get; set; } = -1;
public Vertex(Vector3 position, int index)
{
Position = position;
Index = index;
}
}
Ah yes, struct limitations
just put it in the constructor
Can't initialize it in a default constructor, as you can't provide your own implementation of it (errors as well)
I might have been mistaken 🤔 it compiles for me as well
And most importantly, works as expected
Ahh it's because you have to init all members before control leaves the ctor
Shouldn't be a problem for you
Hello! How would i fix this? Im unsure what its asking me.
When i press Play in the editor, it works fine for the first time the scene is loaded. if i get to the end of the level and reload the scene, This comes up ^^
wdym
Talking to myself lmao
When you create an empty struct constructor, you have to initialize all its members inside of it
Otherwise it yells at you
struct S {
int x;
int y;
public S() { // error, 'y' is not assigned a value.
x = 42;
}
}
Actually pretty sure it's illegal to have a zero-property struct constructor at all.
Yep, the errors just stack up
"The field or propety 'whatever' must be fully assigned" or something like that
Looks like that might finally be changing in C# 10 though https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#parameterless-constructors-and-field-initializers
Oh you were talking about the parameterless ones
Yeah, they changed it
That may also be why it was compiling on my machine, .NET 6 installed
@fresh salmon any ideas on solving my issue
Just scroll up, I made a snippet
Like, right there
Well, it doesn't work in Framework, so it will not compile for you
The good old foreach loop it is then
error CS0568: Structs cannot contain explicit parameterless constructors
so it doesnt work in unity?
It will not
i read something were default structs are allowed on c# 6
what version does unity use
C# 7 or 8
But
What we're talking about is parameterless constructors, which were implemented in C# 10, which itself was released less than one week ago
Unity definitely doesn't support that
but default structs should be supported then
since its c# 6
do i have to change a setting or something
Read my messages again
structs i mean
Field initializers in structs are not supported. That's what your error was about
Assuming MyStruct is a struct
public MyStruct() {} // Not allowed, until C# 10
Your VScode isn't configured properly
public int Index { get; set; } = -1;
That = -1 part
Is the problem
That's a field initializer
Nah I also have suggestions for refactorings in VS, even if they're not supported yet. No error in VS, errors in Unity
Not supported until C# 10
oh ok
VS prompts me because I have NET 6 installed, but it shouldn't be. Something going on with VS's Unity integration
It simply does not check for the current project version and/or doesn't disable analyzers for other installed versions
Anyone know?
Anyone has any idea why every time i press play i get a null reference exception pointing to my unsubscribe line? The game plays normally and everything seems to be working fine btw including the event logic. Hair pulling stuff
does that class execute in edit mode? In any case, it is trying to find an instance of that FoxlairEventManager that has been destroyed already... which happens before you enter playmode as a part of the edit mode cleaning up.
OMFG thanks dude. I had a leftover [ExecuteInEditMode] above the class🤦♂️ FML
because your singleton instance is likely being destroyed before this object.. Is your action in FoxlairEventManager static? If so, you can just omit Instance from that line
(and in your Start() method)
Oh, oops, Anikki already answered, too. I was going to say something about unity doing weird things if your manager is executing in edit mode but he beat me to the punch
*shakes fist at @compact ingot * you're too good, my friend
Me me, mines not been answered
nah, i've just been there
where is it?
Is that a reply to me?
👆
Need a little more information, I think? like the code where the errors are happening nevermind i see you posted it, reading
you need to set the frame buffer to the render texture, then grab the render texture pixels, and then set the frame buffer back
I have no idea what that means
sec
so I am adding animation to my game and I had 2 variables for moving horizontal and vertical but not since I have the animator variable I dont know what to do. In the move_input function I put player_animator for the vertical and horizontal but for move_direction the vertical_move and horizontal_move is still there because those are floats and i will get an error when I try to use player_animator.
using UnityEngine;
public class Movement : MonoBehaviour
{
Rigidbody rb;
public float speed = 5f;
float drag = 6.9f;
public float move_multiply = 10f;
public Animator player_animator;
//if i made it public then i would have to set avalue like a dumb ass
float horizontal_move;
float vertical_move;
Vector3 move_direction;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
player_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
move_input();
PlayerDrag();
// "Vector3 move_input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));"
// "rb.MovePosition(transform.position + move_input * Time.deltaTime * speed);" this is a basic rigidbody movement code
}
void PlayerDrag() //makes the player not slide like ice
{
rb.drag = drag;
}
void move_input()
{
player_animator.SetFloat("horizontal", Input.GetAxisRaw("Horizontal"));
player_animator.SetFloat("vertical", Input.GetAxisRaw("Vertical"));
move_direction = transform.forward * vertical_move + transform.right * horizontal_move; //when we the player looks to left or right the movement will continue to go the way the player is looking
}
private void FixedUpdate() // so our movement is smooth af
{
movement(); //calling the move thing
}
void movement()
{
rb.AddForce(move_direction.normalized * speed * move_multiply, ForceMode.Acceleration); //the epic movement comes into play
//normalized makes sure the magnitude is just 1
}
}```
I read what you said but honestly have no idea what you're asking for help with.
I will say it seems like you're never writing anything to horizontal_move or vertical_move, so they will obviously not do anything for you.
i think that yield return null; might be a problem, also, you might need to do an explicit RenderTexture.active = null after releasing the render texture.
I need help with player movement and it will not work since the variable player_animator is not a float
so I do not know how I will replace the vertical_move and horizontal_move
Should i just make it a normal void @compact ingot ?
Shouldn't you be reading those values from input? What does the animator have to do with it?
just don't skip ahead one frame right when you want to take a screenshot
that GL.Clear is probably not needed or should execute immediately in any case
i am adding animation the my player movement so when I move it will show it walking
just don't skip ahead one frame right when you want to take a screenshot
What would i use instead? wait end of frame? or just dont have a coroutine
don't clear the frame buffer, just use what's already in there (should be clear anyway); or if you want to explicitly render a camera you'd just use Camera.Render()
the animator is irrelevant to the movement code. Ignore it
Get your input values from Input.GetAxis etc.. as normal
if id ont add it then when I walk it wont show it walking
You already have that part working
using UnityEngine;
public class Movement : MonoBehaviour
{
Rigidbody rb;
public float speed = 5f;
float drag = 6.9f;
public float move_multiply = 10f;
//if i made it public then i would have to set avalue like a dumb ass
float horizontal_move;
float vertical_move;
Vector3 move_direction;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
// Update is called once per frame
void Update()
{
move_input();
PlayerDrag();
// "Vector3 move_input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));"
// "rb.MovePosition(transform.position + move_input * Time.deltaTime * speed);" this is a basic rigidbody movement code
}
void PlayerDrag() //makes the player not slide like ice
{
rb.drag = drag;
}
void move_input()
{
horizontal_move = Input.GetAxisRaw("Horizontal");
vertical_move = Input.GetAxisRaw("Vertical");
move_direction = transform.forward * vertical_move + transform.right * horizontal_move; //when we the player looks to left or right the movement will continue to go the way the player is looking
}
private void FixedUpdate() // so our movement is smooth af
{
movement(); //calling the move thing
}
void movement()
{
rb.AddForce(move_direction.normalized * speed * move_multiply, ForceMode.Acceleration); //the epic movement comes into play
//normalized makes sure the magnitude is just 1
}
}```