#archived-code-advanced
1 messages Β· Page 150 of 1
Hi, I have a question regarding some VR coding that I am doing, I am unsure if it belongs in here or in general (or maybe even beginner lol) but thought I would add it in here since the added factor of VR might make it a bit more challenging unless im being stupid! (Please point me to the right place if this is the incorrect place)
But I am currently working on a project where the user has a video camera that they can pick up and look through and on it I have a screen on a "stalk". I want the player to be able to grab and rotate the stalk and screen while holding the camera.
I have a version of a script to manipulate an object with 2 hands (thanks to following a Valem tutorial on youtube!) however I am now sure get it to rotate just the stalk and the screen (marked on the screenshot in pink) rather than the main Base of the camera. And also how I can assign a secondary attach transform for this object so I am grabbing it at the tip rather what is currently happening where I am just burrowing my hand in the main camera
Question regarding Animator Override Controllers and Animator Parameters - when changing a runtime animator controller it seems that the animator's parameter state is reset to defaults. Is there a way to capture and restore this state when changing controllers? I'm aware of the animator.parameters array, but it is read only and seems to only be a reference to the parameters, not what state they are in. Just going through each parameter by hand seems stupid, as they could be ints or floats or bools and I don't fancy making three separate dictionaries just to store the state for one instant.
Can Someone Tell me i want to Move my Ai in a 2D maze what should i do as Navmesh doesn't support 2D and A* path finding isn't working
well, as someone who is baffled by how incredible A * is, I can tell you that A* pathfinding does work, and I have yet to see one example of it not working.
if you're using A* pathfinding and it isn't working, it probably has something to do with some of the values you've set. I'm struggling myself to understand how to properly implement pathfinding, but I've seen it in action, it does work. what exactly is the issue you're facing rn?
My object isn't really moving towards it's target just standing their
i have never used it before maybe that's why i don't know how should i set the values and all
well I'm no expert on it.
I'd recommend checking out
https://www.redblobgames.com/pathfinding/a-star/introduction.htmland https://www.redblobgames.com/pathfinding/a-star/implementation.html
to get an idea of what you're working with.
Ok i will give it a look maybe it helps, Thanks
Most people are probably going to sleep or waking up around these hours.
If you have a lot to add, consider creating a thread.
oh geez I forgot threads existed
should I just copy what I put above and just delete it from here to clear things up? @iron pagoda
it's not an issue, really
but you can copy all the relevant stuff to the new thread
I am trying to generate a bunch of Rects that represent different areas of the map based on an integer, for example if the integer is 4 it will give me 4 rects that accumulate the entire map. Obviously with a number like four this is easy, because I can just divide the width/height but what about numbers like 13 how would I evenly split it up still?
Hi, Any better way to handle it?
Suppose I have two vectors (source and target direction). I would like to rotate the source direction towards the target direction but with arbitrary value (It is possible to reach and even exceed the target direction)
var normalVector = Vector3.Cross(sourceDir.forward, targetDir);
var q = Quaternion.LookRotation(sourceDir.forward, normalVector);
var lookRotation = q * Quaternion.Euler(0, _desireAngle, 0);
I cannot use Quaternion.FromTo or Quaternion.RotateTowards because as I mentioned, I do not want to rotate exact between source and target direction
So add that arbitrary value to your true target direction and use that new dir
?
The rotation you want should be given by Quaternion.AngleAxis(normalVector, _desireAngle); you should be able to apply that to either sourceDir.rotation or sourceDir.forward depending on whether you want a Quaternion or a Vector at the end of it.
I illustrated it. See purple vectors. I want them
Red: Source vector
Green: Target vector
maybe target vector is misleading
Quaternion.Lerp?
no
It is between source and target
I want to start from red vector (source) and rotate x degrees towards green vector, maybe reach or not or even exceed, pass
Like I said, Quaternion.AngleAxis is the function to do that.
It is true
var normalVector = Vector3.Cross(sourceDir.forward, targetDir);
var lookRotation =Quaternion.AngleAxis(_desireAngle,normalVector);
Instead of
var normalVector = Vector3.Cross(sourceDir.forward, targetDir);
var q = Quaternion.LookRotation(sourceDir.forward, normalVector);
var lookRotation = q * Quaternion.Euler(0, _desireAngle, 0);
The problem is :
Quaternion.AngleAxis(_desireAngle,normalVector);
It does not start from source vector like my solution
var lookRotation = q * Quaternion.Euler(0, _desireAngle, 0);
As I said, it's a transformation; you apply it to your source vector or quaternion.
ive now translated the ini reader dll to be readable by both c++ and c# code, if you wanna have a sneak peak xD
although ill change the functions themself to something way more performant in the near future*
how do i know if a playerpref isnt set yet. Can i do something like this : if(playerprefs.getfloat("something") == null)
while idk exactly what a playerpref is, undefined variables in c# are usually null iirc, so if youd expect something != null u could say ```csharp
if (playerprefs.getfloat("something"))
{
//...
}
thats checking for anything but 0
ill try thanks
checking in the signed range, so anything greater or less 0
you can Simply check if it's 0 or not
thats what ive just said
this doesnt work because it acts like a bool and its a float so its an error
hold on
i dont want to know if its 0 or not i want to know id the playerpref is set or not
PlayerPrefs.HasKey is the function you're looking for; it will return true if something has been set for that key, false if not.
oh thanks ill try
Yes that's the function just slipped my mind
sorry i thought in a c++ context it seems c# doesnt allow this type of conversion
then just check
so this will work? if (PlayerPrefs.HasKey("something") == false)
if (playerprefs.getfloat("something") != 0)
{
//...
}
Should do, yes.
it will work like this if(playerpref.haskey("Playerpref Name"))
IT WORKS THANKS EVERYONE
@echo meadow No problem β€οΈ
why is c# so unforgiving with type conversion
maybe that's what it makes it different or i don't know better
@dusty shell i got you on the first too i am also a C++ programmer i use java c++ and C#
C++ is not more forgiving than C# with type conversion
not more forgiving but it allows more direct access
parents are always non-forgiving
and thus you have more freedom on accessing data structures
i mean ive even accessed and called from a c++ class in assembly
and dont ask why i needed thatπ€£
to accessing is fine but creating data structure hell for me
well it took me 5 hours to figure this
how i can access a const char* in c#
answer is
[DllImport("INI_Reader", EntryPoint = "INI_Reader_get_value_string", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr INI_Reader_get_value_string(IntPtr INI_Reader_Instance, int index);
public static string TypeCastString(IntPtr str)
{
return Marshal.PtrToStringAnsi(str);
}
answer from me would be Just quitπ
im not used to c# so excuse me good sir
well i am not into C++ much bcoz i left C++ about an year ago i am very comfortable with C# and Java
ive written an ini file reader dll
which exports for both c# and c++
so both server and the unity client can use it
having more work once to reduce workload later on
Good may you work more and well
There's no need to cross post, #archived-networking was the right channel
yes i know but that chat is dead and nobody is helping there
You waited all of 4 minutes
Did you get anywhere with this? I read it just before I got in the shower and ended up drawing grids in the steam on the shower door π
!warn 847490760119025706 Don't crosspost.
!Apan#1828 has been warned.
well now i have waited 3 hours and like I said, no answer
I'm glad you learnt patience, don't ping me
maybe you can find some soft of middle ground between those options
i didnt, i replied
Again, do not ping me
i didnt
unless you turn off the @ when replying, a reply will ping
@echo meadow Obviously not that many people here will know photon, so you will have to wait a long time to get an answer (if any)
alr
your question is also light on details
nah I dont think so
Well we'll see if you get an answer then π
Hey yall, I just added the AstarPathfindingProject in my project and before i even started using it it threw the warning:
Use of UNITY_MATRIX_MVP is detected. To transform a vertex into clip space, consider using UnityObjectToClipPos for better performance and to avoid z-fighting issues with the default depth pass and shadow caster pass.
any suggestions of how to hide it or fix it?
Looks like a Shader from the asset is using a deprecated function
Seeing as its a pathfinding asset you can probably just remove the shader
have you tried new object pooling API?
https://dotnetfiddle.net/qqgiOy got any idea where in this script? This is teh script that pops up when i tap on the warning
Test your C# code online with .NET Fiddle code editor.
line 18 obviously
but I was saying just get rid of the whole shader. It's probably for an example
still not sure how to properly get the path back from the found tile lol. thread #913319758512918590 show's what I got so far. any insight would be appreciated c:. thx for the help I've gotten so far,
Is there any way to modify prefab instance HideFlags in scene? I have tried using PrefabUtility.GetPrefabInstanceHandle and modify hideFlags there, but with no success.
If you can get a reference to the instance's Object can't you just modify it directly? https://docs.unity3d.com/ScriptReference/Object-hideFlags.html
With the plain game objects everything is fine, but I have a problem with prefabs. For context: I am creating a tool that sets hideFlags to HideFlags.NotEditable for a specific game object in scene, but if the specified game object is prefab and reloading the scene the hideFlags from that prefab is set to None. So I need a reference to this particular PrefabInstance like the one in yaml scene file.
Are you using UnityEditor.PrefabUtility to save changes to your prefab by script? (https://docs.unity3d.com/ScriptReference/PrefabUtility.html)
I don't need to save changes directly on prefab, but on the prefab instance in the scene.
If you open unity scene with text editor, there are PrefabInstances with overrides, and I need to set hideFlags on it, but I'm not sure if this is possible
Ohh, I misunderstood - well I think you can still use PrefabUtility to save instances in the scene, though alternatively you may have to either use AssetDatabase.Save and .Refresh with options (https://docs.unity3d.com/ScriptReference/AssetDatabase.Refresh.html) or System.IO and write to the file - however I found with Editor scripts, using System.IO doesnt update Unity directly until you force a recompile, so youll probably need to call AssetDatabase.Refresh anyway - im guessing cause the scene is open/in-use your changes probably get reverted to a cached instance of your scene that Unity reloads if you dont save changes to the scene (this is my assumption, I cannot confirm that bit)
Looking at one of my projects, these "instances" use a "FileID", so if you want to change that, youd also have to know what "FileID" is referring to, and which ID you need - I assume those are probably the HideFlags values your referring to, but the value is an int, and I have a feeling the int index for the enum flag, probably wont match what Unity expects that "FileID" to be
@versed nest thank you very much, it make sense, i'll try tomorrow
Any way to block the Editor during a long async operation without actually blocking the main thread? the closest I could find is using
EditorUtility.ClearProgressBar();
But that only displays a progress bar without actually stopping the user from interacting with the Editor.
probably can try a modal dialog
They don't really do what I want to, they seem to be used to give the user a choice, I just want to perform a blocking operation
Running it on the mainthread will do that -_-
sounds like you don't want a blocking operation but you want the UI to be disabled during your nonblocking operation
YES! exactly that
I just want to ensure that the user (me) won't accidently trigger an assembly reload and thus break the long operation
EditorApplication.LockReloadAssemblies()?
https://docs.unity3d.com/ScriptReference/EditorApplication.LockReloadAssemblies.html
Prevents loading of assemblies when it is inconvenient.
any reason getComponent wont work on all scripts? I have a script that can't be disabled and I can't detect it to interact with it so my check is always false
GetComponent works on all scripts. It doesn't care about enabled/disabled.
The lack of checkbox there means you don't have any relevant lifecycle methods on it. I.e. no Start(), Update(), FixedUpdate(), etc..
what's always false?
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 2.2f, layerMask))
{
Interactive InteractiveAgent = hit.transform.gameObject.GetComponent<Interactive>();
Debug.Log("Interactive? " + !!InteractiveAgent);
if (InteractiveAgent != null) // HIT
{
You should really add some logging so you know what you hit
Debug.Log($"Raycast hit {hit.transform.name}");```
You might not be hitting the object you think you're hitting
Also can you show the inspector for the object you're hitting? Does it have any parent or child objects with colliders/Rigidbodies?
the parent does have a rigid body and collider, it's effectively a button on a vehicle
but the parent is on a different Layer
so it shouldn't matter?
but I am detecting multiple hits
its like the layer mask does nothing
It's possible you configured your layermask wrong
Also note that if the parent has a Rigidbody that hit.transform will return the Transform of the parent.
You want hit.collider to get the actual collider you hit
layerMask = LayerMask.NameToLayer("Interactive");
layerMask = ~layerMask;
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 2.2f, layerMask))
{
this is wrong
Highly recommend setting up your mask in the inspector:
[SerializeField]
LayerMask layerMask;```
Or if you really want to do it in code, you use GetMask:
```cs
layerMask = LayerMask.GetMask("Interactive");
layerMask = ~layerMask;```
NameToLayer gives you the layer index not a mask
OH, that explains a lot
also transform.TransformDirection(Vector3.forward) can be simplified to transform.forward
true
I seem to only get results without a mask and just comparing the component
either way, this is a huge step forward - thank you for pointing this out
using the serialized solution works directly π
Without using a custom inspector, is there a way to show a different set of parameters/fields/struct in the Inspector per a choice of enum in the same component?
no
Thank you! that works perfectly
{
"body": "{\"Item\":{\"id\":\"1\",\"SettingsEntity\":{\"CategoryIcon\":{\"Address\":\"https://hidden-v2-test-contents.s3.eu-central-1.amazonaws.com/settings/category-icons/category-askeladden%404x.png\",\"Name\":\"Askeladden 2 XR\"}}}}"
}```
Hello. I made a request to my backend and got this string as a result. But this is not a json-looking response and comes in body.
so I got confused with what type of writing style this is
any idea?
thanks
This looks like a formatted json
It's a normal JSON string sent in the body
the \ are just escaping the " inside the other "
hmm. I will serialize this string. So probably, I need to remove slashes first before I serialize them.
no, read the body and it'll "remove" the slashes automatically
well the output is messed up a bit
even if the slahes are gone, you still got {} inside "" which does not make sense
did not get it. why do you say so? how should I handle the serialization?
Did you write the backend code yourself?
Depending on what you're showing, it's either a normal JSON response or a double-stringified JSON
the {} declare some kind of object, which has values which follow YourValueName: YourWhateverValue with or without "". and of course array [] you can {} put into. "" are only for values you want to have besides numbers like int
hm.
So if you use node.js, I am sure, there is some kind of REST Api to help you out there
Node.js - RESTful API, REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every compon
thanks!
I'll have a look. I have always escaped learning a backend language but I think its time.
from the examples this is a pretty straight forward thing to do I guess
p. sure this is a client-side issue, unless of course the server sends the response in a silly format
Just had the words in mind "did it myself". How do you get your call from the API? @mint sleet
I send HTTP get request to my endpoint.
it triggers lambda, was written in node.js, returns this string as a result.
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName : 'hidden-v2-settings',
/* Item properties will depend on your application concerns */
Key: {
id: '1'
}
}
async function getItem(){
try {
const data = await docClient.get(params).promise()
return data
} catch (err) {
return err
}
}
exports.handler = async (event, context) => {
try {
const data = await getItem()
return { body: JSON.stringify(data) }
} catch (err) {
return { error: err }
}
}```
this is the node.js code working in the backend.
ok yeah that's a silly format
You could try just return data instead of return { body: JSON.stringify(data) }
looks perfect π
Is anyone able to help me with some movement logic? I'm setting the enemy to run backwards, but it's waiting until it gets to the next waypoint before turning - I'd like it to turn straight away; code incoming oops... This is in "Void Update()"
{
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * enemy.speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.4f)
if (enemy.fearEnemy == true)
{
Debug.Log("Backwards");
GetLastWaypoint();
transform.LookAt(target);
}
else
{
//Debug.Log("ONWARDSSS");
GetNextWaypoint();
transform.LookAt(target);
}
}
What is the target ?
if (Vector3.Distance(transform.position, target.position) <= 0.4f) this doesn't have any affect on anything. You have no brackets for it, and there is nothing on the next line.
I would say, that your LookAt target and the waypoint target need to be two different vars. Running backwards will be different values.. running forwards will be the same values.. if I've understood what you're trying to do
Empty lines are ignored so it does affect the next if statement
should always use brackets though
Target is the waypoint that is set along the 'path' it follows
That line is detecting how close it is to the "current waypoint" and then changing it to the next waypoint
It's set at 0.4 so the unit looks like it's moving properly
I haven't been able to work out how to put the "fearEnemy" check in before-hand so it will hopefully update (target) to be the previous waypoint - ergo move backwards
But as it is currently, the enemy will only move backwards once it reaches "waypoint 12", before going back to "waypoint 11"
That's the full script just in case
please use pastebin or similar π
Sorry - will do!
I'm close though... almost tasting it
It's BEER TIME! - in case anyone was curious; http://pastie.org/p/3ysSE2WwwWo0EUpGPieXGe
Feel free to help me tidy up the code π
This isn't true though
It only affects the next statement, regardless of how much whitespace there's between
The if statement was working before... I could change the value and it would act different and if I removed the line completely then the enemy would move from Start > Finish without following any of the ~14 waypoints that are set
btw there's no point in checking the same condition twice here:
if (enemy.fearEnemy == true)
{
if (enemy.fearEnemy == true && runBack == false)
{
Good point... In terms of "streamline/efficiency" how much of a drain do double-checks like that affect the program?
Cool cool, I wasn't trying to be an arse with the question lol but I'm slowly seeing all these lines of code building up
also if (x == true) and if (x == false) are usually written as if (x) and if (!x)
I don't know what you mean but you probably misunderstood
I guess it's changed in a newer version of C# ?
https://social.technet.microsoft.com/wiki/contents/articles/37763.c-if-else-statement-curly-braces-or-not-an-in-depth-analysis.aspx Putting this in VS now, doesn't give the same result as this article states
Technical articles, content and resources for IT Professionals working in Microsoft technologies
if (enemy.fearEnemy == true && runBack == false) --> if (enemy.fearEnemy && !runBack)
Nope, always been that way
This is what I meant - you were just representing 'x' in the way we use 'i' in loop examples
Is there a preference/best practice on checking things to be false, over checking them to be true?
I'll have to check the article, there might be some detail I don't know
I don't know if it's mentioned in any guidelines, but personal preference is to check for positive in if-else statements
if(condition)
{
DoPositive();
}
else
{
DoNegative();
}
instead of if(!condition) { DoNegative() }... etc
if you have an if without an else then you don't have a choice
Okay cool. I was just thinking if it was quicker for a false to be checked than a true since you wouldn't be "looking for anything" - as in, the code will see that there is 1 character then return as true, false would see there isn't any characters - but in a true check you may be comparing long names or values
This is likely to be a minimal problem with computing power these days so it's just a best practice thing really
If there's any difference, the compiler can do the optimization much better than you can
and for booleans it'll have to check the bit state in either case
Roslyn probably doesn't do as much optimizations as you think it does
Awesome, thank you very much! I was thinking it could be used for null checks and such but likely getting ahead of myself
Sorry to keep asking here - I've expanded my "Enemy" with ~15 lines of stats... when would I look at moving those to a new class "EnemyStats"? For my eyes I'd like to have it collapse-able in the inspector and load it in the enemy script - Array/multidimentional array? - but at the mercy of the code
yes a custom class or struct would work well and would be collapsible in the inspector automatically
Cool, thank you very much. Is the logic that you don't want parse through code more frequently than needed? So... The code loads "Enemy" loads "Stats", then only loops round Enemy until Stats are eventually called again?
Therefore - each loop of "Enemy" is only 30 lines of code, instead of 300 yadda yadda?
uhhh... I'm not sure I understand what you're talking about.
I'm trying to understand the theory as to when/why you break/split code into a new class
To split up responsibilities and prevent code duplication. Enemies might have Stats and Allies or Players might also have Stats
So right there you can reuse the Stats code instead of writing it in multiple places
Also stats may be something that exists outside the context of an enemy. For example you might be comparing the stats of something to its potential stats if a new piece of armor were equipped. You don't want to have to have a whole instance of Enemy to do that.
Ohh okay, I see. Thank you very much for the explanation. In my case only enemies will have these stats but I understand the logic
With that in mind, would 'you' put the enemy stats in another class?
~140 lines of code at the moment... before I add the rest of the status functions
Although... I should maybe split that out π ahhhhhhh the choices xD
I have potentially a dumb question, is it possible to set a string parameter of a method to the name of a member that is set in another parameter.
private float _age;
public void Save() =>
SerializeValue(_age);
//...
public static void SerializeValue(object value, string name = "")
{
// automatically have 'name' be "_age".
}
No
it is. unfortunately that is only possible in .net 6. and unfortunately unity has not yet migrated to .net 6. you can do it manually though
incorrect
Still impossible in unity, but was not aware of it being in net 6. What's the syntax?
Out of curiosity, what is the method to do this in .net 6?
And manually you mean nameof(_age)?
yes, just pass nameof()
linked above^^
wait let me check, it might be the wrong one i linked.
yeah sorry. that's the one: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0
@urban warren that's the one^^ was mistaken before
Ah cool
I was going to say, I thought I had seen that other one before.
um yeah i just skimmed the text and it looked like it was the one i was referring to. but it was not.
I think CallerMemberName is the one I found previously that made me wonder if it was possible.
and well, i guess it might even be available earlier than .net 6 unity because it actually only requires C# 10 support
Unity only supports up to C# 9 so far right?
yeah
Oh well, guess I will use nameof(..). Just trying to cut down on boilerplate.
well you can just pre-write the C# 10 version and just comment it out for the time being with a TODO or smth
Yeah, I hope C# 10 will be supported soon, but who knows how long it could take.
it's just been released so i am certain that it will be in 2022.1 at the absolute earliest. probably maybe more like 2022.2 with backporting to 2022.1
Got another question. So if I have two dictionaries, but one of them with the keys and values swapped (so a key of one is the value of the other). The second one would not take additional space, because it uses the same data, or am I being dumb...?
You're not being dumb, just wrong
So it would take up 2x the memory then?
(Yeah, I know I'm not dumb, just being dumb π I should know this but it just ain't clicking right now)
Yes, with some caveats
I see, I was hopeful :/
If you have objects that only exist in the dictionaries, then they don't take twice the memory because you only have the objects + 2 references to each of them
Yeah the dictionary only contains references to the objects. So double the references, and the objects themselves only exist in memory once
Assuming they're reference types...
Yeah, I'm working on a save system and needing to be able to both get and set UnityEngine.Objects by id or reference :/
Should be fine then, you're not duplicating the objects
The ids are structs though.
also it'd probably be error prone because a KEY cannot exist more than once, a VALUE can. if you swap a dictionary you might lose some elements
Swap dictionary?
keys/values swapped
Oh, that isn't a problem, they would both be added or removed at the same time.
I feel like there is a better way to do it though. But I'm not sure what it would be.
i mean if you have the same value for multiple keys, that works, but if you then swap the pairs for the other dictionary, you would lose all elements except the first one that had that value because now it's a key
This is what I'm thinking of.
private Dictionary<UniqueId, Object> _idObjectMap;
private Dictionary<Object, UniqueId> _objectIdMap;
public void Add(Object obj)
{
var id = UniqueId.NewUniqueId();
_idObjectMap[id] = obj;
_objectIdMap[obj] = id;
}
this is fine except wouldn't it make sense for the UniqueId to just be a field on your class?
then you only need one dictionary, the ID -> Object one
your object -> id mapping is present on the object itself
I need to keep an entry for every GameObject and component.
Another option would be to add a component to every GameObject which contains the id and an idea for each component.
Or something like that.
whats the goal here? Persistent IDs for GameObjects in a scene?
Save system. If a UnityEngine.Object field is saved I need it to save a ID instead so that on load/deserialize the id can be used to find the object again and reassign it.
yeah exactly
definitely give these objects a component
You can generate a unique id for them in onValidate for that component
is that only per session? cause if it's supposed to be over multiple sessions, id's won't work anyway
"PersistentId" component or something
Why wouldn't IDs work?
well, i don't actually know what id's you're referring to, but if you are thinking of unity's internal object id's, they are only valid for the session
No, custom UniqueId struct (serializable wrapper around System.Guid)
ah well ok, that should work then
Yeah, I guess a component would work better for storing the id of the object. Think I should do it for every object, or just manually for the ones that could be referenced. I feel like doing it for every one is overkill, but doing it for only ones I know(think) will be referenced seems like it is easy to miss one and it not be loaded.
only for the ones that you need this referencing behavior for.
I'm imagining this is for something like... coins or pickups in a level that shouldn't be there anymore when the scene reloads after you've collectd them, right>
Yes and no, this is for saving a full game. In this case a farming-ish game. So stuff like player position, inventory, crops in the world and their state, etc.
would be nice if unity just had a snapshot feature
Gives me an idea for an asset store asset actually π€
Isn't that what Git is for?
SCENE snapshot for saving. not PROJECT snapshot.
context dude
Indeed indeed, I ran out of that on Monday and I won't get another delivery until next Monday ^_^;
Would be nice if Unity had a save system π
A snapshot feature in Unity would be pretty much impossible and impractical.
well, maybe you should take the time off this chat till next monday then ^_^
For 1 you'd have to make sure all of your game data was serialized and referenced from scene objects
which ... nobody does that
For 2 you'd have to save a ton of data that is essentially duplicate data from the scene file
that'd make save files unwieldy
Ohhh, I was trying to lighten your mood. It's (almost?) the weekend!
I got another memory question. I am trying to decide if it makes more sense to save whole components, or to have an interface with OnLoad/OnSave methods where you specify the fields to save/load.
and i'm (almost) pissed because people keep rambling about irrelevant shit.
sorry
that'd really be a non issue if you have a game where state is important. better to load a snapshot than a new scene
depends. Look at something like Factorio or Minecraft. Those games are 100% state. It would work there.
Then look at something like Mario. It would be 95% duplicated scene data, 5% game state
Such a thing could work, but only for certain games
minecraft is not 100% state. mobs will not be saved e.g. redstone ticks afaik are not saved, .....
That's an argument against a snapshot system, isn't it?
but there is no basic level geometry etc. is what I was getting at
and i'm not saying that that would be the default save system, but that it'd be nice to have at least the option
Guess what 99% of beginners would use if that option exists
guess why 99% of games are shit and shouldn't even exist
hehe fair enough
For a save system for an 'advanced' game, I am having a hard time deciding if I should have Savable component that I add to gameobjects that has a list of components you want to save on that gameobject and just save all of the values on each component. Or, if I should have an interface that components implement where you specify which fields are saved and loaded.
Thoughts?
My concerns are possibly bloating the save files with lots of unnecessarily saved fields, and possibly saving fields that shouldn't be. But I'm not sure how much of a concern those really are?
The interface thing worked fine for me in the past
The only downsides I see to the interface is that A, it is more work, and B, not exactly sure how to handle 3rd party components.
what you need is a serialization lib, some code that manages entities generically, and some way to flag a component for serialization
that flag can be an interface / attribute for your components
for third party you write something like SaveComponentResolver<T> where T would be third party component
like its done here https://www.newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm
in any case the bulk of the job i would delegate to the library, and specifically tailor it for unity
did that some time ago
these days i avoid this approach instead having any persistent data separate from components that use it
Of course, I am not planning on making my own serializer. Basically what it comes down to is the management of GameObjects and Components and how to save and load them and their references.
mark, do it in phases
when serializing you convert references to ids, when deserializing you first construct the objects then link them
Yes, that is my plan.
there are numerous problems with components tho
i.e. you need to track comp id in the prefab, and if you change it, it breaks
haha yeah i really dislike the idea now
I will have component ids by GameObject ID + Component type
But again, my question now is either to save all of a component, or only the values that are needed.
Idk how much bloat would be caused by saving everything
if you have a library you can extend it with your own attributes
i.e. change the default json.net behavior
How does that address my current quandary?
you only save what you need
you need the value - slap an attribute on it
need it in third party asset - do that through jsonConverter<T>
Ah, you are saying use attributes to denote values to save.
yeah
depends on the implementation
- compared to an interface approach
still depends
if you have your properties mapped and at least converted to delegate get/set, then it should be about 10% slower to set
other than that its up to serialization lib
yeah also the lookup would cost some
Only to a point. Unless there is cheaper way to get attributes than normal old reflection, it will be quite a bit slower. At least to initialize
yeah you have to cache it on launch
thats what i assume most serializers do
the biggest footprint will be allocation
the rest is peanuts
also linking, depending on your graph complexity
You mean reattaching the references?
yeah
Ah, shouldn't be more than a dictionary lookup
can be, depends
In what way could it be more?
I mean it will be more if it has to insatiate a prefab
if you for example have to exclude cyclic references, or you have order dependent linking, or something like that
Ah, I think that should all just work without any special handling
actually if you are going to go the manual route, maybe skip interface all the way and just use the Save<T> approach
so ```cs
class MyComp : Component{}
class MyCompSave : Save<MyComp> {}
just a satellite class dictating how to save it
How is that different than using an interface?
How does it support third party?
class ThirdPartySave : Save<ThirdPartyComp> {}```
Oh, oh. You mean how you were talking about like the JsonConverter.
yeah
i would opt for one single method, cleaner and more expressive, and separates serialization from the class, less clutter
tho you lose private access
This is kind of what I was thinking. Also 'doubles' the number of classes in the project.
However it does prevent the 'main' classes from being cluttered
you can keep them in separate namespace
right in the file
private access, depends on implementation
you can do that through cached reflection
you cant avoid it with third party
I think I will do some tests, see what feels nicer to write and check the performance of that vs using newtonsoft json using DataMember
Thanks for the input, ideas and thoughts π
if you decide to go with interface/manual you can use odin, its forward only and should be quite fast
there are also zeroformatter/messagepack which should be fastest
Forward only?
ZeroFormatter hasn't been updated in like 5 years which makes me wary of it.
plenty of choice!
ello. trynna do some pathfinding things and somehow I messed up what probably should be one of the easiest things I guess
I have it check all 4 directions out from a tile, and if its not a collider, and it hasn't already been checked, it then sets that tiles weight to 1 higher than the center tile, and adds it to the checked tiles. I also add the center tile to the checked tiles
so the middle tile weight should be 0, and the tiles around it should be 1.
but instead the middle one gets 4 added to it, and the tiles around get 1,2,3,4
more in depth on muh thread about it: #913319758512918590 (might not show up on some phones :L)
open the wiki page for astar and implement the pseudo code there
man I've been working on this for days lol. I've been reading up on this stuff. I simply messed up the logic in a part of my code somehow. it finds the tile, and would find the path find if the weight got assigned as I expected it to.
just trying to debug
lol
I've managed to get it into a working state.
however for some reason when it makes the path back it always loses the last 2 squares for some reason
I need help figuring out how to rotate my character without using normal information, as surface normals orient my character the wrong way. I DO have access to raycast, position, and delta position information which I believe should suffice for calculating a rotation. I also believe that an extra raycast (towards the left) is useful to make sure the player is oriented correctly even more. Can I get help calculating the rotation?
I have a gaussian distribution system that I managed to get working for shotgun spread with slight randomness, but it only works if you look in one direction.
It's a Vector3 array, with a length of...let's say 12. Is there a way to make the vectors move so that they are always in front of an object, like a shotgun barrel?
I then generate a bunch of rays, each of which point to a point in the Vector3 array, and then the shoot function takes care of the rest. However, if I look in a different direction, it still shoots in the same direction, as the "cloud" of points never actually moves.
Any ideas?
strange question, but im wondering if it is possible to make a tick-based system in unity. Physics would only happen on these ticks, absolutely all physics. for frames between these ticks, interpolation and such would be used to generate the image. (this is my understanding of the source engine's inner workings)
of course that'd be possible. if you only for for physics then you could also just decrease the standard physics ticks
okay, that's cool. dunno much about unity but its cool to see it's malleable (ew thats not the word im looking for)
I think if you pay Unity enough money they'll give you full access to the engine source code
And I believe it is for large enterprise only
It would be difficult for a single person to have enough money to license the entire engine, anyway.
That's pretty much how the default physics system works, assuming you enable rigidbody interpolation
Can somebody recommend me a good dependency injection lib for Unity?
What kind of functionality would you want from a dependency injection library that isn't provided by gameobjects and the scene hierarchy?
What do you consider the correct orientation, if surface normals are wrong? In my experience the difficulty with problems like this usually comes in figuring out what behaviour you want and expressing it rigorously; once you've done that the actual maths tends to fall out automatically from the description.
Let me show you the expected result
constructor or method or property injection mainly
I found Zenject that seems to do all of these things and much more
The player must orient relative to the surface between 2 points
But the problem is when the normal is even slightly tilted, it completely shifts the player's rotation
especially with spherical shapes where at the poles the player drastically changes rotation
The yaw and pitch are might as well fine, but I think the roll is the issue
So the player's local "up" should be the vector from the blue sphere to the red sphere? And the player's local "backwards" should be away from the surface?
The player should be oriented towards the normal to prevent going through the surface, it's just that the roll does not comply with the surface normals
(With the first requirement more important than the second.)
I need to somehow make the roll camera relative so that surface normals don't screw it up
That's why I thought of using these 2 points
The problem is knowing the math
It sounds like the problem is basically just that you're only using one vector to determine the orientation (or rather one vector and the world "up"); you need two. So when the world up is equal to the normal you don't get consistent behaviour, since that second vector is missing.
I tried quaternion lookrotation but it never worked as expected, likely from my own incompetence
How do I make an up vector then?
If you have a second vector from the blue and red points then LookRotation should be what you need; it wants forward and up vectors, so I would have expected LookRotation(-normal, red-blue) to give you sensible results.
red-blue is a direction, correct?
Yeah, as in subtracting the positions of those two.
Nope, the pole issues are still present
(I am lerping between n1 and n2, )
How are you generating the red position?
Through a raycast on the triangle
Sorry, I mean how are you generating the raycast? What determines which direction it's in its offset relative to blue's? Because that difference is going to be the primary thing that determines what your character's "up" is.
I then record the triangle index and barycentric position, meaning no matter how much the triangle deforms it always stays exact (this is for skinned meshes)
The direction is based off the player's current position and shifted by camera-relative input
So if you hold "up" on the controller then the red point should always appear above the blue point on screen, right? Is that the case?
But if you scrub through this video you'll find frames where the red point is below the blue point (in screen space); was this a result of you pressing down while recording it?
Oh sorry, I enabled forward-based movement
Meaning I move relative to the roll
The erratic teleporting was me clicking on the points
Basically there are two points where this approach can go "wrong" in the case where you're holding up; either the red point sometimes moves below the blue in screen space, or the character sometimes orients with their head towards the blue rather than the red. As long as red-blue is of non-trivial length and different from the normal, using LookRotation should guarantee that the second doesn't happen.
What do you mean the second?
So I'd guess that either (1) the points are generating in a way you don't expect, or (2) you're applying this logic when red-blue is almost zero or almost parallel with the normal, so LookRotation odesn't have two different vectors to work with.
The points are generated as they should expect
Basically you always need a minimum of two non-zero, non-parallel vectors to generate a sensible orientation. If one of your vectors is zero or the vectors are parallel, it has no way to know what roll it should use around the one vector it has.
The main issue here is the roll
Should I cross product then?
Cross the normal with an Vector3.up?
That won't help when your vectors are up or zero already, which is exactly the case you're having trouble with.
But my vectors aren't up or 0
Look at the arrows
they are normals, if they were 0 they can't generate
Sure, but that's a screenshot from a frame when it works correctly, right?
No. Check the video - the normals are always generated perfect
they are calculated from the actual triangle edges themselves
not from raycasting
I'm not suggesting that the normals coming out of the red and blue spheres are zero, I'm suggesting that the delta between the red and blue points might be zero (or colinear with the normal).
Let me debug log the delta between red and blue
Values seem to be natural
My guess is to try and make the roll face the direction of the points, God knows how I do that though
Because the roll is in relation to the yaw and pitch, so if the surface normal changes the roll is seriously affected too
I'm not sure what else I can tell you; all I can suggest is to find a frame where the resulting orientation isn't what you expected, look at all the data coming in on that frame (basically just red point, blue point, red normal and blue normal) and follow the calculations through to see which one isn't doing what you expect.
This doesn't happen within the span of a single frame, this is simply just the normals taken wrong
I'm sorry, then I don't understand what problem you're describing any more.
Alright, how about I try to orient the player based off the direction of the line? Forget the normals
It also deforms along the deformation of the surface since it has 2 points, but now I need an up vector, because it keeps twisting
Anyone have any idea how to work with the new code trimming functionality introduced in .Net 6? Specifically how I can tell the compiler to not trim a third party package?
Unity makes this so easy with the Link.xml file anywhere in the project directory pensive
Canβt use .net 6 with unity
Yes. This assumes the maps square and you're trying to generate square rects but it works.
var start = (mapDivisor / 2) * -1;
int chunkSize = mapSize / mapDivisor;
for (int x = start; x < mapDivisor / 2; x++)
{
for (int y = start; y < mapDivisor / 2; y++)
{
var rect = new Rect(x * chunkSize, y * chunkSize, chunkSize, chunkSize);
}
}
Hey all, I'm trying to work out the best way to do some math... So, I have Enemy waves and I have boss waves... I would like it to be intuitive in that, if my scene has 11 enemy waves and 3 boss waves... the boss waves will appear at 33%/66%/100% of the enemy waves - or if there are 15 enemy waves and 6 boss waves etc...
The boss waves are at a * n / b where a is the total amount of waves, n is the boss wave number and b the total amount of boss waves
Wow, thank you very much. a = enemy + boss 'wave'
Correct, I'm creating a stand-alone .Net 6 tool for use in Unity
float accelerationForce = 0.5f;
public Transform targetWorldPosition;
public Transform missilePosition;
public Rigidbody targetRb;
public Rigidbody missileRb;
private void FixedUpdate()
{
/* Calculating Time to impact*/
// First find the time difference Vm = d*t
// d
float dist = Vector3.Distance(targetWorldPosition.position, missilePosition.position);
// Vm
Vector3 relativeV = (targetRb.velocity - missileRb.velocity);
// time
float timeToImpact = Vector3.Magnitude(relativeV) / dist;
/* Calculating Prediction Position */
Vector3 predictedTargetPosition = targetWorldPosition.position + targetRb.velocity * timeToImpact;
/* Add force to rigid body */
Vector3 aimPoint = predictedTargetPosition;
Vector3 aimPointDirection = (aimPoint - missilePosition.position).normalized;
missileRb.AddRelativeForce(aimPointDirection);
targetWorldPosition.position = targetWorldPosition.position + new Vector3(0, 0, 0.05f);
}
I have this missile intercept code, but my msisile doesnt turn and shoots under the object. any clue why?
- You're not rotating the missile.
- the force you'r adding is probably tiny.
Sorry, I'm trying to break this down and I don't "have" 'n'; all I have is 'a' and 'b' at the moment... and I'm trying to get/set when 'n' is amongst the normal enemy waves. Currently I just count up on enemy waves and I'm trying to introduce "intermediate" waves, with the last wave("final boss") just incorporated into this - should I create another coroutine for "final boss" just to help with the math/setup?
You need to calculate the boss waves by running through all values of n. If you have 3 boss waves then calculate with n as 1, 2 and 3.
but it would be much easier if you just defined the system as having x normal waves before a boss wave, and how many bosses you have. For example, 4 normal waves + a boss, which repeats 3 times (= 15 in total)
I made this system where the On-Screen Stick joystick in unity is enabled and disabled depending if a finger is touching the screen or not, but im having an issue when i touch the screen and move my finger really fast to another point that the joystick doesnt detect and follow my new finger location, any help?
ping me if you answer plz
If I were designing everything myself to know that's how it works, absolutely lol. I am being a pain by making waves appear at 1/3, 1/4 waves depending on the "boss wave" value but I clearly do need to iterate through it all. The worst bit is making the final boss the actual last wave sigh.
Surely that's the easiest part
if current level == total number of levels, then it's the final boss level
For simplicity, if I was to go if there are 12 enemy waves and 3 boss waves, a boss wave would appear at a multiple of 5? so 12+3 = 15, 3 boss waves at 5-10-15...
yup
Hah, case and point I should give up for the day xD
L=N+B
I=L/B
L=Total Levels
N=Normal Levels
B=Boss Levels
I=Boss intervals.
Am i missing something?
If youre basing boss levels based on number of waves it really depends on how much bosses you want on average.
yeah, that's the same as my formula but with the terms moved around
That's pretty much what I couldn't picture right now, I'll set a counter and then when [x] = blah... that makes actual sense!
I'm going to blame it on staring at it for too long but appreciate the logic so much!!
As this is my first game, the biggest thing I'm trying to get over it optimising everything "from the get go"
If I could see that people have scripts with 1000's of lines of code then I'd just get on with things any-which-way lol, so I tend to over ask
Diving into unit testing soon, anyone have advice on how to approach unit testing specifically in the context of Unity and game development? I've heard conflicting thoughts about unit testing with Unity, and would like to get a holistic picture. Overall it seems like low ROI spending time writing robust test suites for 3D development because there is so much you need to test and simulating user input and specific scenarios can be such a hassle, but I feel like as our industry grows there will be more of an expectation and need for Unity unit testing
Any thoughts or advice would be greatly appreciated π
Well I guess first thing to point out is that there are different levels of automated testing. You seem to be using unit testing and integration/functional testing interchangeably. There certainly is some expectation of automated testing in Unity already, considering that Unity is building new tools for automated testing.
@hushed fable Which parts of what I said could be interpreted as interchangeable? I was referring specifically to unit testing but as I mentioned Iβm green to it in general, so Iβm curious what part of what I said would not apply to unit testing
I speak specifically from the context of XR development where you canβt unit test specific methods without going into runtime and recreating a specific user input scenario, especially with hand tracking
Odds are most of the code in the XR project isn't that specific to XR, but XR is just used as a input method.
I'm not the right person to draw the boundaries between these different levels of automated testing, but if you are setting up an environment where you have a chain of classes interacting with each other and you are validating the results of multiple classes, then I would say you are doing something beyond just unit testing.
Cool, thanks for the clarification, that makes sense
I need help with the quality of my assets. For some reason it looks good on the unity editor but when I hook my phone up to see what it will look like its all very low quality and looks like shit. Any help please?
@mild quiver Don't cross-post, and not a code question.
Oh sorry wont happen again.
How do I make a text box show the speed of the player (And what do I put in the player controller script) I am using the roll-a-ball project for this
Is it a rigidbody and you move it via physics?
It is the same script that is in the roll a ball project on the asset store
I see that you asked in #π»βcode-beginner , which is actually where you should've asked, not here.
Oh ok
Also is there a way to move a part of a prefab for a player model because I want to make it so where when I jump the arms on it move it is using the "Full Body FPS Controller" asset
CoinsPerRun = CoinCount.coinAmount;
if (Player.Shadow)
{
distance *= 5;
}
distanceNo = distance;
distanceText.text = distance + " m";
if(distanceNo > HighScore)
{
//HighScoreSet = true;
PlayerPrefs.SetFloat("Highscore", distanceNo);
}
if (player.isDead)
{
InvokeRepeating("Dead", 0.001f, 0.001f);
results.SetActive(true);
finalDistanceText.text = distance + " m";
if(distanceNo > HighScore)
{
HighScoreText.text = distanceNo + "m";
}
else
{
HighScoreText.text = HighScore + "m";
}
}```
This is the** UI controller Script**...(a part of it) So In here when Bool Shadow is true i want to multiply my score with 5... And it does work, but the problem is After when bool is false(Shadow) it goes back to the deafult score instead of Continuing** from the multiplied Score...
Hey, I have quite a weird question here about Unity, AI, and evolution. (FIY, I'm not an advanced programmer, just wanting to know if this is possible so please don't use alien-language π ) Would it be possible to entirely simulate physics and electricity into one game? I'm trying to find out if it's possible to make an AI that basically lives a simple human life: he sleeps; finds food in a shop and eats; dies; works; communicates. I'm quite sure 4 of those are easily possible, but with "working" I mean a person (or whatever you want to call that little robot) who figures out how to develop/expand his country through communcation (aka, there's a lack of food or water / there's a dangerous animal killing all of them: he notices and communicates) and finds solutions to those problems by inventing machines. Like better water irrigation techniques, improved defence systems and maybe other sci-fi stuff that doesn't even exist on earth. These '"robot-invented" machines would then of course work according to the laws of physics. The process of inventing would basically work by:```
- Giving the AI basic knowledge once he gets spawned
- Trying things (like that game called Little Alchemy) by fitting different combinations of mechanical parts together.
- Testing whatever they make
- The process of testing can result in for example: an explosion if there's a bad circuit; a working prototype (which would be classified as working if it actually does something the AI can notice: like raise the oxygen levels (it produces oxygen), or produce food much quicker).
- All of the knowledge it has gained by trying out different combinations will be saved and shared with all other AI's, in order to make sure he doesn't make the same mistakes.
I know this would be extremely complex, but all I'm asking is: is it possible in Unity?
If you manage to "entirely simulate physics and electricity" you get to pick up your Nobel prize the next year, so the bad news is that it's probably not going to happen
The good news is that you can definitely make a game like that but with a simplified set of rules instead of a full physics simulation
Haha yeah.
What I kind of meant but didn't say - so that's on me - is that it would just be an island (no planets, universes, multiverses, etc.) where the AI lives.
But good to know that it's possible. I would love to do something like this one day and see how my country evolves and takes ov- ehmm. Maybe not such a good idea
I'd have to find a way to enable emotions to make sure no one kills each other for money lol
But how about the part where the AI should remember its outcomes? I'd rather not keep killing them and keeping the good ones, but instead have one that keeps surviving and it just learns
So basically unsupervised learning
I mean, AI unsupervised learning is something alright.
How do you know it won't learn that falling on it's face on the ground instead of in the water is the best way to survive, because it lasted longer than everyone else before dying?
If you can do that in Unity, people would be lining up to hire you everywhere.
hahah true
But I don't mean to use the unsupervised learning for learning how to survive. That would of course be done best by evolution
You could design your loss function to account for that
I mean the inventing things part
So like, the AI wants the highest score, but it loses points when it fails, and gains points when it does well?
But that would seem really hard to make. After all, how would you simulate greed in an AI?
Or is there an easy way to set a goal, like reaching the highest score?
This is not very clear to me, Physics doesn't really work like this lol
Like, at first I know what you mean by simulating electricity and physics, but the next part is just bizarre
It seems that you want an already abstracted and gameified world, yet you want some elements of it to obey the laws of physics
ehmm
I would say, if your entire game world was determined by the laws of physics then it would make sense
Yeah
but having some subset of "machines" that follow the laws of physics would not make sense, since those machines must interact with the rest of the game world via the laws of physics, and hence the whole game world must also evolve according to the laws of physics (including your character)
that's what I mean. But not all laws of physics are needed, as all I'm creating is one country. Not an entire universe
exactly
Fpr example: it would be easier to just use Newton's laws and not general relativity as we aren't dealing with big masses
I don't think all the computing power in the world can fully simulate the motion atoms in a glass of water, let alone an entire country
there are like 5 * 10^24 H2O molecules in a litre of water
You are going a bit too deep into the laws of physics I'm looking for. And yes, for everything to be 100% accurate, it would need all of these rules, but it's fine if it's not a 100% accurate
What do you mean by "not 100% accurate"?
you were the one that said "an entire country"
not 100% accurate to how it would be in real life
I only know of countries in real life
What does that mean?
like, precisely
The problem with very small systems is that they get stuck in loops or dead states, for example look at Game of Life
Okay let's just forget all of the above, and just imagine this: I'm a simple AI, my goal is to invent stuff which my population needs (it knows what they need through communication: don't think about that for now). For example: my people are in need of better protection against the big bad wolf. 99 scientists (AI's) and myself go to work by experimenting different combinations of circuits/mechanical parts. (Think about minecraft's redstone system but just expanded). We then make something --> Test --> see what happens, and then learn from that. Of course simple physics, like gravity and resistance should be taken into account. But getting into atoms, complex chemical reactions, etc. would just be too complicated. So of course, there are restrictions to what I'm able to do
To make it a bit more realistic, I'll have to include force, and if an AI gets hit with a certain amount of force, it dies
I think it would be very hard to create something interesting or useful, but you should try and make a prototype
Indeed
You should probably check out Dwarf Fortress
I should start small, and expand as I go. But what I need to figure out, is how to make an AI learn from those experiments by remembering?
I will
Hmm, looks interesting and I see what you mean. I'll have a look π
Isn't this "irl-human"-controlled though? The little creatures don't just do it themselves
I guess it would be possible to automate those commands by looking at what the population needs though. Thanks this helps
Yes, this isn't the exact thing that you are looking for, but it is still the deepest simulation that someone has made (that I know of), but they still need commands
it is a resource intensive game though
you need a good CPU
the key to all this will be in making the right abstractions in your simulation. You should aim at making your simulation produce believable results, and those can be created by much simpler means that simulation complex systems with high accuracy
most of what you need can be created by a system of utility functions and a simple planning system
The problem is that I'm not aware of anyone who has managed to do this yet. Of course Dwarf Fortress arguably did it, but in that case he is a genius and did a postdoc in Mathematics lol, and has been doing it for 15 years
forget about learning and ML in general, that is a wholly different aspect of AI
that math degree didn't enable him to make DF
its just something that makes certain things easier to grasp
That still has a massive impact
i'd not overestimate that
@lime plover what other games have you made?
Still, I'm not aware of someone who has created anything like @lime plover is describing
but I do know many have tried
anyone Used A* path finding Package i need help to set it up
As I said in the first post, I'm definitely not an advanced programmer. And regarding the games I've made... well I feel it's sad to say there's not much to talk about...
I always get distracted about other things and just completely abandon those projects
Well, this is just about the hardest project you could possibly choose
hahaha
but how about doing it in smaller steps
the invention part is probably something I'll do later as that's the hardest
Did that work for your other projects?
I have no clue because only 1 of them are finished so far lol
The problem is that I come up with more ideas than I can make
Well it's okay to come up with more ideas than you can make, that is a good thing, the problem is whether or not your ideas are actually possible
yea
the thing in this case is that a simple prototype of what you're describing could take years to produce
But what I'm trying with this project is to figure out what to exactly do first before actually doing something. Usually I just start somewhere and eventually find out I wasted 20 hours because there's a much easier way
Hmm why though
Because you want to create an extremely detailed simulation of life and machines, and have autonomous robots learn to intelligently design them lmao
xD
Most games have very simple, well known rules and parameters
I think you're overthinking my thinking.... I first just want to start out with a simple navmesh agent/ai that's able of completing easy tasks, like walking to a lake and drinking, or planting a carrot and eating it
Like I said earlier, I want to start small and expand later on
I just need someone with a whip who forces me to continue working on the game. Otherwise I'd probably get distracted
Every time I say that your idea is complicated, you drastically reduce the scope of your idea π now it's just a villager that moves between nodes depending on if it's hungry or thirsty or thinks it should plant food? I thought they were going to be designing circuits and machines with gravity, forces, and friction??
xD
yes
eventually
It's not like humans just popped out of an egg and started building rocket ships
nono, they first started doing the basic things
like killing each other over and over again
first with rocks, and now with nuclear missiles
there's a big gap between those
Well now we're at an idea you can probably implement, yes, a village that has a bunch of specific tasks that can be simulated, and have weather and stuff, and the villagers automatically learn how to manage the tasks to best survive. That's still a massive task, but it is possible
ooohh weather is something I haven't though about yet. Good idea.
And good to know it's possible. I'll figure out what I exactly want first before making it this time xD
If you're going to implement a system like that, why have an AI do it? It sounds like gameplay.
I think it's like when Lisa accidentally creates a civilisation in that Simpsons episode
Yea, but what I want is my own civilization which runs on its own. I don't have enough friends to simulate that for me lol
Hahahaha yes indeed
anyone who have used A* path finding need help
post your question and whoever can help will do so
need help in A* path finding i placed the Package and set everything according to a tutorial but it's not working
Do you mean Aaron Granberg's A*?
yes
Check here
They don't have a discord
But usually if you want help with a specific package you're best to search their community
well i didn't get anyhelp from the internet so i thought if anyone here has used it before
Good luck! I haven't used it yet. Planning on picking it up soon
i need to make a 2D Ai to move in a maze any other solution?
My plan is to use that library, but you can also use unity navmesh
There is a 2D fork of it that I'm using by a github user named h8man
Does the job pretty well, although it's a tad confusing
navMash is not for 2D
You can find it on openupm
Read the messages I wrote
you are using it ?
Yep.
Works nicely
It's just a fork of the default navmesh package with 2D collider detection
how to set it up?
@void topaz
ok i am going to Use it and if i stuck somewhere will contact you
Sure. You know how to add it?
how?
You can add it to your package.json
"com.h8man.2d.navmeshplus": "https://github.com/h8man/NavMeshPlus.git#master"
You'll need to have git installed, which I assume you do given that you're asking in #archived-code-advanced
yes i do have it
*manifest.json I mean
are you free could you help me on a call? to speed up the work
i need to submit my work in the morning so
It's 2am for me
I'm about to go to bed
sorry
got my own work to do
If I were you I'd try to get AG A* working before switching
It should work, it's like a ten year old package.
More mature than unity pathfinding even
i have tried A* according to the tutorial but nothing happened that's why i thought it will be good to switch bcoz i have used navMash in my soo many games
I can't comment.
On account of not having used it
As I explained
thousands, I never used A* or navmesh before cause I always custom code in a solution, you can use steering behaviours, flow fields, object avoidance.. so many different solutions.. Also not sure if this belongs in advanced code, general code would probably be a better fit. I also made an asset for this https://assetstore.unity.com/packages/tools/ai/rts-flow-field-movement-system-149474
man if only you were here days ago @leaden jungle lol
I wound up making a pathfinding script from scratch
Doing this can lead to the AssetDatabase returning two versions of the same asset.
Please ensure that code which attempts to reimport this asset does not run while the editor is Refreshing.
You can do so by checking the value of EditorApplication.isUpdating```
- What do I do? I'm scared of losing my work
use a version control system. as simple as that.
for this specific case, if youre trying to use PrefabUtility editor script to load asset, it's already telling you to wait until EditorApplication.isUpdating becomes false
i am using one
@tough tulip
I don't understand what this error means, or the solution it's suggesting
afaik I'm not using a 'PrefabUtility editor script to load asset'
Never heard of this before
I have some questions about saving data (Inventory, characters stats) on mobile for easy cloud storage.
1 - Should I use json or binary formatter
2- Use a save all in a file or separate files e.g. one for inventory, another for characters stats
Thanks
For future proofing, I'd go with Json/xml/any other text based format instead of Binary formatter because a previously saved binary formatter file might not work when you do some changes in class declaration. Text might not always be ideal when it comes to security, so you might wanna add another layer of that
then you have nothing to worry. if you're not importing prefab, make sure it's not some Asset store package which is trying to do so.
It's also possible that it's a unity error (probably from some Beta/Alpha version)
How does the stack trace look for the error?
Thanks
that was all it said
Yo, I have a few networking related questions
I've been making a game in a JS engine for a few years that compiles client and server code separately. The server holds positional data and etc. and communicates it periodically, while the client has all the visual stuff, which is pretty standard.
I'm thinking about transitioning to unity and rewriting it here, but there are a few parts of netcode that're tripping me up:
- It seems like most guides/docs indicate the "standard" is just to check if you're on the server or the client midfunction. Is this more efficient than separating the code with partial classes & #if flags and having two separate builds? I'd imagine this is just the easier way for a doc to explain netcode
- The docs mention a Host as well as a Client and a Server. I'm not really used to the concept and don't understand the difference / how it'd be present in the same tut as I understand hosts to be a p2p concept.
this seems much more my speed in terms of what I understand, but I'd want to change my norm if it's notably less efficient than what unity suggests
I'm using nested canvases to avoid expensive rebatching, however, I'm still a little confused how UGUI.Rendering.UpdateBatches works... UpdateBatches is still taking 30ms+ when trying to add 4-5 new UI elements and nothing else changing.
Hey guys, how do I turn this "Emission" On by code? In Edit mode
I have tried everything and the only thing that seems to work is copying from another Material "material.CopyPropertiesFromMaterial(baseMaterial)"
Hey, in order to make an ai remembering combinations (like: little alchemy) I thought of making 3 string arrays. 1 for the ingredients, 1 for the purpose, and 1 for the name. Would this be the best method?
the idea is fundamentally that you build just one app that can be used as either client and server such that you get maximum benefit from sharing code, no need to create an elaborate protocol and minimize inconsistencies. Now while that also enables you to do what you describe. i.e. check for isServer or isClient mid-function, that is a generally a terrible architecture. as it gets confusing very fast.
Like you described, the better way would be to instead have 3 classes/components/partials for everything that is network related: Shared, Client and Server. Client and server parts have a reference to the shared components and you implement stuff with the strictest separation possible.
The other thing is that all common unity netcode libraries are server authoritative and they want you to make sure all your code is 'safe', i.e. that clients cannot change the game state without explicitly being given authoritiy to do so. This leads to certain patterns that look very awkward when inside the same class, but it is just the same as if you'd develop a server and client as separate apps (splitting into client/server/shared parts helps keeping this separation clearer)... you are just tempted all the time to take shortcuts. There are certain additional patterns and conventions (depending on library) that are sort-of required for your own sanity, like only ever changing a SyncVar with changed-hooks through its changed-hook (when using Mirror) . Some you may have to come up yourself, and often you don't get much help in figuring these out.
why not make a class
Depends what shader it is
Standard shader also this doesn't seem to work for me "material.EnableKeyword("_EMISSION")"
What Unity version?
Probably because I have no idea what that is lol
2019.4.16
I can set a new material for it "material.SetTexture ("_EmissionMap", textureRef); "
but I cant enable it
Also doing it this way is annoying because its not really copying, its referencing.
"material.CopyPropertiesFromMaterial(baseMaterial)"
which makes it harder to reassign my original textures
google it π
I believe this should work. It's not changed or different for that version. I think you're just seeing the issue where for some reason you need to interact with the material inspector to get it to refresh. I forget if there's a workaround
I thought so too at first, but I couldn't get it to refresh, let me try to use force refresh
didnt really want to use editor code in this script
your right, I couldnt make it recompile though with:
AssetDatabase.Refresh();
however, I set a value to the Emissions and it is visible
omg I wasted so much time on this thanks for the help
It's a crappy bug, I have no idea if it's fixed on newer LTS versions
ok, here is something weird, if I do anything on my script and force unity to recompile, it reverts back
so its just.. temporary lol
I will try a different unity version and see if I can replicate I guess
I've not tested it at all, but in addition to using EnableKeyword you could try to modify the materal like this:
#if UNITY_EDITOR
var so = new UnityEditor.SerializedObject(material);
var keywords = so.FindProperty("m_ShaderKeywords");
if (string.IsNullOrEmpty(keywords.stringValue)) {
keywords.stringValue = "_EMISSION";
}
else if (keywords.stringValue != "_EMISSION" && !keywords.stringValue.Contains("_EMISSION "))
{
keywords.stringValue = $"_EMISSION {keywords.stringValue}";
}
/*// Disable keyword - if you want this to be a toggle (also needs handle "_EMISSION")
else
{
keywords.stringValue = keywords.stringValue.Replace("_EMISSION ", "");
}*/
so.ApplyModifiedProperties();
#endif
(I've not tested this, even whether it compiles, also if I was to write it properly I probably wouldn't be testing for keywords like this)
thanks, I will give it a shot
It works the same way, and gets reverted back in the next recompilation stage
The effect is apparent in the Scene window, however the bool is still false in the inspector
but then it gets reverted in the next recompile
I also tried this on 2019.4.33
Damn, well, other than going through its importer I've got no other ideas. I've got to eat, so maybe someone else will come along who's dealt with it before
thanks a lot bro much appreciate it
unity default rp or any srp?
hi where can i learn C hashtag
google?
I think the problem was I was calling this in monobehaviour instead of editor script
that said, I found a way to do it in mono but its a round about way
Anyway thx
you mean c#? btw it's pronounced as "C sharp". google is full of c# resources. I personally like youtube videos interesting and I think this may be really good introduction series: https://www.youtube.com/watch?v=N775KsWQVkw&list=PLPV2KyIb3jR4CtEelGPsmPzlvP7ISPYzR
does someone know what O(dtβ΄) is in the context of velocity verlet ?
it means additional terms are "on the order of" (delta t)^4
it's a small change approximation
Presumably they mean (delta t)^4 multiplied by any of the non-delta vectors (x, v, a, da/dt, etc)
ah that makes sense
you can derive the actual value by evaluating the Taylor series at t for +dt and -dt:
x(t + dt) = x(t) + v(t) (dt) + a(t) (dt)^2/2! + a'(t)(dt)^3/3! + a''(t)(dt)^4/4! + ....
x(t - dt) = x(t) - v(t) (dt) + a(t) (dt)^2/2! - a'(t)(dt)^3/3! + a''(t)(dt)^4/4! + ....
So:
x(t + dt) + x(t - dt) = 2x(t) + a(t) (dt)^2 + a''(t) (dt)^4 / 12 + ...
hm, I wonder if Discord has math notation
You can copy/paste symbols, but I think that's it
Ty for the reply, read it this morning while skimming some docs and itβs been massively helpful
Hey there. I recently saw a video about an AI which was trained on a ton of coding examples, and which eventually able to finish a piece of code which you told it to do. For example '''This function finds the average of an array of integers''' and it would actually do this (of course not 100% accurate every time though). I was just wondering if this would be possible with conversations too. You would then train it on a bunch of conversations, from beginning to end. Would it then actually respond like a normal human being would?
Don't they use pre-programmed messages? For example: you have a list of words, and if your message contains any of those words it just tells you the same message?
there are so many neural network driven chatbots, you would not believe
most of them are trained on users interacting with it, but I would assume they are provided a base-level of data to start the training from (i,e. potentially pre-programmed responses that evolve over time)
otherwise it would take forever to train them
Alright, thanks
Hi! I'm using the INK pluguin for flexible dialogue, but when I try to select one choice the story does not continue
anything special i need to know before i build a framework for unity? building an RPG framework with economy, character creation, spell / abiluty creation, item creation, and stat management,
parsing a float does depend on system culture
You should always specify a culture when parsing string numbers
Unity's Vector3 ToString might always use a dot
Haven't tested it
perhaps - but the default ToString is not really suitable for serialization anyway
It only prints 1 or 2 digits of precision depending on your Unity version
it's intended for debugging
sounds like a fair call. I am building myframework as a console app hah.
Hello, I'm wondering how I can show the current graphic card memory used which is shown in many mobile games (for example 2GB/4GB => smooth). How can I do that if it's even possible?
(ex. of GTA V)
A quick google search shows that fetching the current usage is not possible
You can get the total amount of VRAM using the SystemInfo class.
I also found out that you can get the total amount but didn't saw anything about it not beeing possible
I saw something about adding all the textures graphic data etc. together
thanks anyway
so I was going to divide up my networking code into _Server and _Client files using a #if SERVER_BUILD tag, but i'm running into issues now where the client isn't aware of ServerRpc functions and therefore throws errors if it's in its own build, which makes sense
but i'm left wondering what the proper way to divvy this up is, then, since I don't think it's a good idea to just recheck isServer/isClient over and over
You donβt use different builds for server/client. They have to be exactly the same.
so you just have it check isClient/isServer in the same function? or is there a superior way?
Well you can but you'd be doing so with your own custom networking protocol.
Most of the frameworks out there assume you're using the same binary on both sides.
Idk about networking but you have to make a shared library that is included in both
Most Unity focused ones yeah, more traditional network libs don't care at all
Do the checking in network start and disable the server/client components as needed. Thatβs why there is a shared component that both keep active.
it feels like it would be inappropriate to give both the clients and the server identical code & etc. when they're only running half (or whatever %) of it
ahh
so you could just have it compartmentalized into different classes
what do you mean by shared component also/what is that component? apologies for the baseline questions, i'm used to a much different style of netcode
thinking about rewriting my game in unity
It is aimed at avoiding inconsistencies and promote easier code reuse
I have explained that in my answer from ~10 hours ago
Like you described, the better way would be to instead have 3 classes/components/partials for everything that is network related: Shared, Client and Server. Client and server parts have a reference to the shared components and you implement stuff with the strictest separation possible.
ahh
yes you did
my bad
i misunderstood, clearly
this makes quite a bit more sense
so for a player controller, you'd have a PlayerController Shared, Server, and Client set of classes, then check in some overarching script which you're on and disable/enable them accordingly
and if you're on the Client, send the ServerRpc for movement on pressing input to the server's version, which has the Server component activated
(?)
Thatβs the approach I find to be a good compromise in effort vs benefit
a dedicated server project is way more effort and harder to test.
yeah I agree, I definitely want(ed) to avoid that, lmao
ty for the guidance, I'm still getting used to the component based system
Components here are usually networkBehaviours that share the same network id
would it be better to, say, attach the three component types ahead of time, then disable them depending, or just attach the shared component and have it add the components depending
That depends if your library works that way usually you are better off building your network objects as prefabs with all components attached in the editor
right, right, makes sense
so, if on a PC_Client I execute MoveServerRpc, it will call that function where- on the server's version of the player, or the server's version of the PC_Client class?
would that cause issues if I'm removing the _Client class on the server since it doesn't need to exist there?
I assume I'd want to put the Rpcs on the _Shared class
Usually for RPCs you will have some kind of options to control where it executes, e.g.: everywhere, only on the server, on a particular client, etc.
depends on your framework of course (sorry haven't been following the discussion, not sure which you're using)
you're good yo, no worries, I appreciate the help a ton
right now I believe I'm just using barebones unity netcode
unsure of the terminology around it
Donβt worry about that, the naming in net libraries is all over the place
also if you run into seemingly silly problems when you just want to do a simple thing⦠unity networking libraries are really serious about authority ⦠so you have to jump through hoops that you could otherwise ignore or that maybe would have never occurred to you⦠usually you can disable authority, which makes networking with trusted clients much easier at the cost of having to rewrite all code when you want to allow untrusted clients later
good to know, lmao, that does sound like a multi day headache that you've saved me from in the future
hmm
I'm checking out Mirror right now
is it notably easier to use something like this instead of base netcode?
they seem very similar in name schemes
oh I see, netcode is its own library
makes sense
It has more readymade components and more community support
it has a less scalable foundation, more compile time checks⦠it overall feels a bit more abstract than netcode
ah alright
yeah I'm pretty alright with the syntax for netcode to be honest, nothing has struck me as particularly weird
it seems more efficient than what I'm used to
neither one will prevent you from completing your project, and neither one is perfect
right right
maybe netcode is better for learning because it doesn't try to help you too much...
in any case if you have advanced requirements, like a really good network transform, you won't get around building your own for your specific project with either one... maybe photon can get your farther there, but at a certain point you enter DIY territory and should leave all libraries behind save for the transport layer
yeah, I figured I'd have to pretty much dive in head first here
I need to support 100-200 players on a single world map ideally so it'll require a lot of custom stuff
which is fine, I've done it already in my existing codebase
just need to learn
thats easily possible if its not a competitive shooter with mirror and netcode... so long as you understand what the general networking pitfalls are
yeah, nothing complicated, just a topdown 2d tile based game
so it's pretty ideal for shortcuts like chunking and etc.
lmao
great
i'm moving partly because the existing codebase i'm using/engine is
so poor with handling that
only recently it moved from just broadcasting all movement updates to everyone on your map
tbh i have come to really detest thick libraries/frameworks, they end up standing in the way more than they help
same
i'd say a library that defines a few nouns and verbs, has an understandable philosophy and doesn't try too hard to please everyone is all thats needed... just a good set of conventions that are well thought out
yeah, the most frustrating thing and part of why I'm switching is not being able to rework how the netcode functions to suit my game
it's annoying a bit to have to code it all yourself but that's not half as bad as being stuck with a kind of alright solution
- javascript's garbage collection issues are
intense
if you worry about GC, you can have a lively debate on the Mirror discord
LOL
mirror doesn't try to be zero-alloc
yeah okay that helps my decision, lmao
netcode largely does
literally
90% of the lag i experience issues with atm on my existing game code
is gc
in netcode you can't send variable length strings for example
Photon Fusion is zero allocation
really all 'advanced" netcode libraries MUST be zero-alloc
Tutorial that explains adding scripts to objects, editor modes (Host Server and Client), basic player movement,Permissions and basic RPC use.
in reference to this doc
i'm assuming the correct way to utilize this and test things is to build, then run multiple copies of the exe
as a server & multiple clients, correct?
then later, just explicitly state a server build when it's ready to be deployed and have that exe be the one that goes on the server itself
and distribute the client vers
i'm gonna save you a lot of hassle and time: https://github.com/VeriorPies/ParrelSync
if you don't like using that "plugin", you can clone a unity project with a symlink, thats the manual way to do testing without building.
i wasted so much time before i wondered if there was a better way...
wow hey it works
well
at the basest level anyway, spawns the player prefab when the server is started and a client connects
but still
sweet
so, now that I have this functioning and can tell when/if something is client or serverside, how would I send an Rpc to the server component of the player controller?
since the server and client components are separate
thats where it gets annoying
LOL
I suppose instead of removing components I could just
hmm
I could put the Rpcs on the shared component?
and use that to communicate
then you have no separation
right...
hmm
I could not remove the components and just disable them instead
and call them that way
but in any case, you have to have that rpc component available on both, server and client
right
so you put ClientRPCs on the -Client part and ServerRPCs on the -Server part and have them called by the shared component. Or if you like, don't use the shared component and call them directly.
its not a separation that always works... you'll need to find your own discipline in it
i find the idea is more important than the rigour of its execution
you certainly want to use the shared component for all connections to things that are not networked
wooo fuck yes it works, thank you so much anikki
i would not have gotten this working without you
that makes perfect sense also
i enjoy this method a lot more than the one employed by my existing engine- there I need to custom define packets per packet, meaning it took several minutes sometimes just to set up a function
If you feel that Iβve saved you some time, Iβm happy
Hi all, what is the Bone index is not within the number of bones. error indicative of? I've set the weights and indices for a mesh manually through Mesh.SetVertexBufferData() (using the BlendWeights and BlendIndices attributes).
I get that and a whole load of Bone weights do not match bones errors in the console
interesting, ty
Kinda hard to say without seeing your code, but apparently you're using an index that doesn't have a corresponding bone to it, just like the error says.π€·ββοΈ
I'm trying to implement gps navigation in Unity. Anyone who has experience with the MapBox API ? I'm going through the examples and it seems that the directions mesh that is produced between Point A and Point B breaks when the map is zoomed in/out. More information here : https://github.com/mapbox/mapbox-unity-sdk/issues/1652 I'm looking for alternatives and whatnot. I even thought of hacking a webview or something so I can use the regular Javascript examples MapBox provides.
Hey
public virtual void OpenClose()
{
switch (!isOpen) {
case true:
layerPanelAnimation.DORestart();
isOpen = true;
break;
case false:
layerPanelAnimation.DOPlayBackwards();
isOpen = false;
break;
}
}```
This is a function in an abstract class. I override it by another script derived from this base class.
public override void OpenClose()
{
base.OpenClose();
}```
Is there any way for me to know if 'isOpen' variable is either 'true' or 'false'
after the base.OpenClose is run.
If it's not private you can just look at it. If it is private then no, inheriting classes can't read its value.
it seems very excessive to use a switch statement on a boolean
just use an if statement
hmm thanks then I will make it attribute and look from there.
yup, switch case usually gets faster than if else chain when there's more than 3 (or smth like that) different cases. switch case for boolean is not the cleanest or fastest code, just use if else
That is such an insane level of micro optimization and has nothing to do with it being a switch but rather a more constrained type of compare & jump at the end of the day.
I just meant it's completely useless and more unclear to use switch case on boolean than if else
return isOpen at the end of the function, and make it a bool function, not void?
public virtual bool OpenClose()
{
isOpen ? layerPanelAnimation.DoRestart() : layerPanelAnimation.DOPlayBackwards();
isOpen = !isOpen;
return isOpen;
}
Hey guys,
I need to write a custom script for a InputDevice.
I already got a InputDevice device; with the correct InputDevice assigned
but now how can I acess the listed values from the image? for example the StickControl VEC2 or the rx AxisControl
huge thanks in adavance, tried to read the documentation about it but did not quite grasp how to
foreach (InputControl con in device.allControls)
thanks π
hey
Ahh, now that's curious - does Mesh.Clear() remove all bones?
Possibly.
I'd guess that it removes all of the mesh data.
But the bone data doesn't belong to the mesh class I don't think? I believe it belongs to SkinnedMeshRenderer
I'll need to probe the documentation further
hey guys, is there a way to change a color field into a button (in custom editor)? there doesn't seem to be an option to change the style of the color field, ideally i would like to change the style into a button that opens the color selection window
Depends on what data you're talking about. There're bone weights for each index telling it which bone to follow. If that data is removed, the vertex is not tied to any bone. Then there's the bone hierachy that the animator moves and the skin renderer ties to the vertices. Not sure of the exact pipeline, but there's absolutely bones related data in the mesh.
@untold moth I get that much - the mesh itself will need bone weight strength and indices per vertex.
For context: I am reconfiguring the attribute layout for a mesh. Backing up previous mesh data, applying the new attribute layout, then restoring that data. All other attributes work fine but the bone weighting data is being a pita.
You might also need to do some work on the skinned mesh renderer for it to update the bones array.π€
Hmm, I'd be surprised if the skinned mesh renderer was touched in any way by modifications to its sharedmesh (besides the changes made to the actual mesh) but I'm no expert here
Either way I'll check that as a possible cause.
if you don't do any other changes, then perhaps there's a flaw in your math. Try debugging the vertex bone indices that you're using.
hey there, I'm bringing this question here 'cause no one could help in #archived-code-general :/
A question about grid snapping. I watched some tutorials and make a little search but didn't found what I was looking for. I have a 3d grid and I want the level to be created using my own tool, only in the editor, not using any code at all for easier level designs. I have a script for placing the tiles in the grid just like this below. The problem is: it doesn't work at all. I have an offset variable that I set in another script called GridManager which is responsible for get connections between tiles and where I have a variable offset to control distance between tiles and I would like to use in this GridPlacer. Reason: I don't want to repeat the offset in each TilePlacer component...
using UnityEngine;
[ExecuteInEditMode]
public class GridPlacer : MonoBehaviour {
#if UNITY_EDITOR
// Update is called once per frame
protected virtual void Update() {
if (!Application.isPlaying) {
SnapToGrid();
}
}
#endif
void SnapToGrid() {
// TODO: calculate position based on grid manager offset
// convert current position in grid position
Vector3 _offset = GridManager._instance.GetOffset();
Vector3 _pos = new Vector3(transform.position.x / _offset.x, transform.position.y / _offset.y, transform.position.z / _offset.z);
transform.localPosition = _pos;
}
}
localPosition is different than position - one is world space, one is local space (relative to the parent, anchors, layout mode, etc)
so .. GridPlacer is a tilt itself? and GridManager is the singleton that holds the offset you want?
So a few orders of business - first, use a static singleton, it's not a great idea to call GridManager._instance (it seems like _instance is a private member in Grid Manager - so make it private - in the GetOffset method, which should be static, locate the _instance and access the private members from within GridManager, not outside in GridPlacer).
I also don't know if you want protected virtual on the Update method - I don't know what that does, but you just make your unity event methods void or private void
Now.. on to the logic, it looks like you're just dividing the position by the offset - all that's going to do is "scale down" the location of your Grid Placer. This isn't going to snap it to a grid, it's just going to uhm.... move things closer to the origin.
Obviously we talked about position and localPosition so you'll have to fix that.
If you want to "snap" something to the grid, then I think what you're wanting is % (the modulus operator) and you want to subtract that modulus from the offset. If I understand your logic right, you want to take the position, get the modulus, and then subtract that from the position (which will snap everything "down/left/toward" the origin, but should work).
@regal olive
ie:
int newX = transform.position.x - (transform.position.x % _offset.x);
thx for replying. I did some changes but not in this message. The actual calcutation is something like:
// get offset from the manager -> _instance is public static, I just missed the naming convention...
Vector3 _offset = GridManager._instance.GetOffset();
// round position for tiling
float _x = Mathf.Round(transform.position.x / _offset.x);
float _y = Mathf.Round(transform.position.y / _offset.y);
float _z = Mathf.Round(transform.position.z / _offset.z);
// recalculate new position for rounded tiles * offset distance for each axis
Vector3 _pos = new Vector3(_x, _y, _z) * _offset;
// apply position to the tile
transform.position = _pos;
Update is protected and virtual because the Tile component for the prefabs are derived from GridPlacer, so this method is meant to be overwritten.
the problem is how to get _offset.x. I got an error:
NullReferenceException: Object not set to an instance of an object
and I believe that happen because GridManager does not have ExecuteInEditMode
you'll need it to ExecuteInEditMode if you want to use it in edit mode π
I'm not sure what this logic is doing but I don't think this works either.. it looks like you're dividing it, rounding it, then multiplying it? you're going to have some really odd behaviour here
again, I think this π is the logic you're looking for
Say offset is 100 and your current item is at 120. You want to subtract the modulus (20) from the current position (120) to get the item to snap to 100.
I'd probably also generalize the math and put it into a static GridManager method like public static Vector3 FindClosestGridPoint(Vector3 location) that returns the nearest point - since your "GridPlacer" doesn't really want that logic, imho
let me break it down again with an example. I'm moving my tile in edit mode with position (3.3f, 0f, 3.8f) and my offset in GridManager is (1.5f, 0f, 1.2f) which means my tiles should have a distance of 1.5f in the x axis and a distance off 1.2f in the z axis of each other.
So, the calculation for snaping in the grid will take the actual position then divide by offset and round down wich will give me 2 for x and 3 for z. And then with this values I have the tile position in the grid wich is (2, 3) then converting to world position I just need to multiply again by offset wich will give me (3f, 0f, 3.6f)
it's not working at all with GridManager :/ I still got the null reference error
K, well, one problem at a time. If the logic is correct (seems to be?) then check for nulls and find out whats wrong (I don't have any experience with ExecuteInEditMode so I don't know what the issue is).
Vector3 _offset = GridManager._instance.GetOffset(); // replace this with some null guard clauses:
if (GridManager == null)
{
Debug.Log("Grid Manager is null."); return;
}
if (GridManager._instance == null)
{
Debug.Log("Grid Manager's _instance is null."); return;
}
(I'm assuming GridManager is an instance of GridManager and not that GridManager._instance is a public static variable)
If it is a public static variable.. well.. probably don't do that. π If GridManager is a monobehaviour then (opinion ahead) I wouldn't access static instance members. Instead, I'd locate the singleton item at Awake() with FindObjectOfType<GridManager> and save the reference in GridPlacer
Hey there, does any of you guys know, if there is way to set defaults for scriptable object properties. Like a have a scripable object that has a reference to another scriptable object and i want that to be set to a default scripable object, when i create a new one.
Do you understand what i mean? :S
If you click on the script for your SO, the inspector will let you set default references for newly created assets.
This only works when you create the asset via the Assets -> Create menu.
I'm trying this now.
But this doesnt work for lists, am i right? From what i know this only works for a few types