#archived-code-advanced

1 messages Β· Page 150 of 1

gleaming thistle
#

I'll keep trying but I'm quite lost on how to do this

tender walrus
#

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

Code : https://paste.ofcode.org/32byWM5nTxpzagRjP27ybvG

elfin temple
#

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.

void topaz
#

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

gleaming thistle
#

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?

void topaz
#

i have never used it before maybe that's why i don't know how should i set the values and all

gleaming thistle
void topaz
#

Ok i will give it a look maybe it helps, Thanks

iron pagoda
#

Most people are probably going to sleep or waking up around these hours.
If you have a lot to add, consider creating a thread.

gleaming thistle
#

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

iron pagoda
#

it's not an issue, really
but you can copy all the relevant stuff to the new thread

gleaming thistle
#

Working on making pathfinding in unity

#

done

dark cedar
#

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?

timber flame
#

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

livid kraken
#

So add that arbitrary value to your true target direction and use that new dir

timber flame
#

?

small badge
timber flame
#

I illustrated it. See purple vectors. I want them
Red: Source vector
Green: Target vector
maybe target vector is misleading

somber tendon
#

Quaternion.Lerp?

timber flame
#

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

small badge
#

Like I said, Quaternion.AngleAxis is the function to do that.

timber flame
#

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);
small badge
#

As I said, it's a transformation; you apply it to your source vector or quaternion.

dusty shell
#

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*

echo meadow
#

how do i know if a playerpref isnt set yet. Can i do something like this : if(playerprefs.getfloat("something") == null)

dusty shell
#

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

echo meadow
#

ill try thanks

dusty shell
#

checking in the signed range, so anything greater or less 0

void topaz
dusty shell
echo meadow
dusty shell
#

hold on

echo meadow
small badge
echo meadow
#

oh thanks ill try

void topaz
dusty shell
#

sorry i thought in a c++ context it seems c# doesnt allow this type of conversion

#

then just check

echo meadow
dusty shell
#
if (playerprefs.getfloat("something") != 0)
{
  //...
}
void topaz
#

it will work like this if(playerpref.haskey("Playerpref Name"))

echo meadow
#

IT WORKS THANKS EVERYONE

void topaz
#

@echo meadow No problem ❀️

dusty shell
#

why is c# so unforgiving with type conversion

void topaz
dusty shell
#

@void topaz just a quick sneak peak on what ive meant

#

xD

void topaz
#

@dusty shell i got you on the first too i am also a C++ programmer i use java c++ and C#

broken basin
#

C++ is not more forgiving than C# with type conversion

dusty shell
#

not more forgiving but it allows more direct access

void topaz
dusty shell
#

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🀣

void topaz
dusty shell
#

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);
    }
void topaz
#

answer from me would be Just quitπŸ˜‚

dusty shell
#

im not used to c# so excuse me good sir

void topaz
#

well i am not into C++ much bcoz i left C++ about an year ago i am very comfortable with C# and Java

dusty shell
#

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

void topaz
#

Good may you work more and well

shadow seal
echo meadow
#

yes i know but that chat is dead and nobody is helping there

shadow seal
#

You waited all of 4 minutes

ivory prawn
hushed fable
#

!warn 847490760119025706 Don't crosspost.

thorn flintBOT
#

dynoSuccess !Apan#1828 has been warned.

echo meadow
shadow seal
#

I'm glad you learnt patience, don't ping me

cursive horizon
echo meadow
shadow seal
#

Again, do not ping me

echo meadow
#

i didnt

cursive horizon
broken basin
#

@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)

broken basin
#

your question is also light on details

echo meadow
#

nah I dont think so

broken basin
hazy hearth
#

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?

sly grove
#

Seeing as its a pathfinding asset you can probably just remove the shader

foggy dew
#

have you tried new object pooling API?

hazy hearth
sly grove
#

but I was saying just get rid of the whole shader. It's probably for an example

gleaming thistle
#

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,

sterile meteor
#

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.

sly grove
sterile meteor
#

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.

versed nest
sterile meteor
#

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

versed nest
#

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

sterile meteor
#

@versed nest thank you very much, it make sense, i'll try tomorrow

pale pier
#

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.

plucky laurel
#

probably can try a modal dialog

pale pier
#

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

olive totem
#

Running it on the mainthread will do that -_-

sly grove
pale pier
#

I just want to ensure that the user (me) won't accidently trigger an assembly reload and thus break the long operation

small badge
cyan shard
#

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

sly grove
cyan shard
#

good to know

#

but then i'm not sure why its always false

sly grove
cyan shard
#
        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
            {
sly grove
#
Debug.Log($"Raycast hit {hit.transform.name}");```
cyan shard
#

it is hitting it- my debug ray is white

#

but its not finding the component

sly grove
#

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?

cyan shard
#

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

sly grove
sly grove
#

You want hit.collider to get the actual collider you hit

cyan shard
#
layerMask = LayerMask.NameToLayer("Interactive");
layerMask = ~layerMask;

RaycastHit hit; 
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 2.2f, layerMask))
{
sly grove
#

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

cyan shard
#

OH, that explains a lot

sly grove
cyan shard
#

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 πŸ‘

glass wagon
#

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?

drifting galleon
#

no

pale pier
mint sleet
#
{
  "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

midnight violet
devout hare
#

It's a normal JSON string sent in the body

midnight violet
#

the \ are just escaping the " inside the other "

mint sleet
#

hmm. I will serialize this string. So probably, I need to remove slashes first before I serialize them.

devout hare
#

no, read the body and it'll "remove" the slashes automatically

midnight violet
#

well the output is messed up a bit

#

even if the slahes are gone, you still got {} inside "" which does not make sense

mint sleet
devout hare
#

Did you write the backend code yourself?

mint sleet
#

No, just found it.

#

it's node.js

devout hare
#

Depending on what you're showing, it's either a normal JSON response or a double-stringified JSON

midnight violet
#

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

mint sleet
#

hm.

midnight violet
#

So if you use node.js, I am sure, there is some kind of REST Api to help you out there

mint sleet
#

thanks!

#

I'll have a look. I have always escaped learning a backend language but I think its time.

midnight violet
#

from the examples this is a pretty straight forward thing to do I guess

devout hare
#

p. sure this is a client-side issue, unless of course the server sends the response in a silly format

midnight violet
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.

devout hare
#

ok yeah that's a silly format

#

You could try just return data instead of return { body: JSON.stringify(data) }

mint sleet
#

let me try

#

πŸ‘

#

thanks @devout hare , @midnight violet

#

it worked.

midnight violet
pastel moth
#

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);
        }    
    }
craggy spear
#

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

devout hare
#

Empty lines are ignored so it does affect the next if statement

#

should always use brackets though

pastel moth
#

Target is the waypoint that is set along the 'path' it follows

pastel moth
#

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

midnight violet
pastel moth
#

I'm close though... almost tasting it

#

Feel free to help me tidy up the code πŸ˜‰

devout hare
#

This isn't true though
It only affects the next statement, regardless of how much whitespace there's between

pastel moth
#

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

devout hare
#

btw there's no point in checking the same condition twice here:

        if (enemy.fearEnemy == true)
        {    
            if (enemy.fearEnemy == true && runBack == false)
            {
pastel moth
#

Good point... In terms of "streamline/efficiency" how much of a drain do double-checks like that affect the program?

devout hare
#

practically not at all

#

probably optimized away by the compiler anyway

pastel moth
#

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

devout hare
#

also if (x == true) and if (x == false) are usually written as if (x) and if (!x)

pastel moth
#

As in x = [variable]

#

So... if X isn't there then it's automatically false

devout hare
#

I don't know what you mean but you probably misunderstood

craggy spear
# devout hare This isn't true though It only affects the *next statement*, regardless of how m...

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

devout hare
#

if (enemy.fearEnemy == true && runBack == false) --> if (enemy.fearEnemy && !runBack)

craggy spear
#

that MS article says otherwise Β―_(ツ)_/Β―

#

anyway, not relevant anymore

pastel moth
#

Is there a preference/best practice on checking things to be false, over checking them to be true?

devout hare
devout hare
#

instead of if(!condition) { DoNegative() }... etc

#

if you have an if without an else then you don't have a choice

pastel moth
#

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

devout hare
#

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

flint sage
#

Roslyn probably doesn't do as much optimizations as you think it does

pastel moth
#

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

sly grove
pastel moth
#

Therefore - each loop of "Enemy" is only 30 lines of code, instead of 300 yadda yadda?

sly grove
pastel moth
#

I'm trying to understand the theory as to when/why you break/split code into a new class

sly grove
#

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.

pastel moth
#

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

urban warren
#

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".
}
flint sage
#

No

drifting galleon
drifting galleon
flint sage
#

Still impossible in unity, but was not aware of it being in net 6. What's the syntax?

urban warren
flint sage
#

That'll give save not age

#

And it's in unity

drifting galleon
#

wait let me check, it might be the wrong one i linked.

drifting galleon
#

@urban warren that's the one^^ was mistaken before

flint sage
#

Ah cool

urban warren
drifting galleon
#

um yeah i just skimmed the text and it looked like it was the one i was referring to. but it was not.

urban warren
#

I think CallerMemberName is the one I found previously that made me wonder if it was possible.

drifting galleon
#

and well, i guess it might even be available earlier than .net 6 unity because it actually only requires C# 10 support

urban warren
#

Unity only supports up to C# 9 so far right?

drifting galleon
#

yeah

urban warren
#

Oh well, guess I will use nameof(..). Just trying to cut down on boilerplate.

drifting galleon
#

well you can just pre-write the C# 10 version and just comment it out for the time being with a TODO or smth

urban warren
#

Yeah, I hope C# 10 will be supported soon, but who knows how long it could take.

drifting galleon
#

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

urban warren
#

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...?

devout hare
#

You're not being dumb, just wrong

urban warren
#

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)

devout hare
#

Yes, with some caveats

urban warren
#

I see, I was hopeful :/

devout hare
#

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

sly grove
#

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...

urban warren
#

Yeah, I'm working on a save system and needing to be able to both get and set UnityEngine.Objects by id or reference :/

devout hare
#

Should be fine then, you're not duplicating the objects

urban warren
#

The ids are structs though.

drifting galleon
drifting galleon
#

keys/values swapped

urban warren
#

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.

drifting galleon
#

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

urban warren
sly grove
#

then you only need one dictionary, the ID -> Object one

#

your object -> id mapping is present on the object itself

urban warren
#

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.

sly grove
urban warren
sly grove
#

definitely give these objects a component

#

You can generate a unique id for them in onValidate for that component

drifting galleon
sly grove
#

"PersistentId" component or something

drifting galleon
#

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

urban warren
drifting galleon
#

ah well ok, that should work then

urban warren
# sly grove "PersistentId" component or something

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.

sly grove
#

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>

urban warren
drifting galleon
#

would be nice if unity just had a snapshot feature

sly grove
#

Gives me an idea for an asset store asset actually πŸ€”

pastel moth
drifting galleon
#

context dude

pastel moth
urban warren
sly grove
#

A snapshot feature in Unity would be pretty much impossible and impractical.

drifting galleon
sly grove
#

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

pastel moth
urban warren
#

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.

drifting galleon
#

sorry

drifting galleon
sly grove
#

Such a thing could work, but only for certain games

drifting galleon
sly grove
#

but there is no basic level geometry etc. is what I was getting at

drifting galleon
sly grove
#

Guess what 99% of beginners would use if that option exists

drifting galleon
#

guess why 99% of games are shit and shouldn't even exist

sly grove
#

hehe fair enough

urban warren
#

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?

flint sage
#

The interface thing worked fine for me in the past

urban warren
#

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.

plucky laurel
#

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

#

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

urban warren
plucky laurel
#

mark, do it in phases

#

when serializing you convert references to ids, when deserializing you first construct the objects then link them

urban warren
#

Yes, that is my plan.

plucky laurel
#

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

urban warren
#

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

plucky laurel
#

if you have a library you can extend it with your own attributes

#

i.e. change the default json.net behavior

urban warren
#

How does that address my current quandary?

plucky laurel
#

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>

urban warren
#

Ah, you are saying use attributes to denote values to save.

plucky laurel
#

yeah

urban warren
#

Apposed to an interface approach

#

I wonder how the performance of that is.

plucky laurel
#

depends on the implementation

urban warren
#
  • compared to an interface approach
plucky laurel
#

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

urban warren
#

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

plucky laurel
#

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

urban warren
plucky laurel
#

yeah

urban warren
#

Ah, shouldn't be more than a dictionary lookup

plucky laurel
#

can be, depends

urban warren
#

In what way could it be more?

#

I mean it will be more if it has to insatiate a prefab

plucky laurel
#

if you for example have to exclude cyclic references, or you have order dependent linking, or something like that

urban warren
#

Ah, I think that should all just work without any special handling

plucky laurel
#

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

urban warren
#

How is that different than using an interface?

plucky laurel
#

it supports both your classes and third party

#

the interface becomes redundant

urban warren
#

How does it support third party?

plucky laurel
#
class ThirdPartySave : Save<ThirdPartyComp> {}```
urban warren
#

Oh, oh. You mean how you were talking about like the JsonConverter.

plucky laurel
#

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

urban warren
#

However it does prevent the 'main' classes from being cluttered

plucky laurel
#

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

urban warren
#

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 πŸ™‚

plucky laurel
#

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

urban warren
#

ZeroFormatter hasn't been updated in like 5 years which makes me wary of it.

plucky laurel
#

plenty of choice!

gleaming thistle
#

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

plucky laurel
#

open the wiki page for astar and implement the pseudo code there

gleaming thistle
#

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

gleaming thistle
#

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

gleaming thistle
#

woot

#

figured it out

royal timber
#

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?

static patrol
#

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?

leaden tangle
#

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)

drifting galleon
leaden tangle
#

okay, that's cool. dunno much about unity but its cool to see it's malleable (ew thats not the word im looking for)

stone quarry
royal timber
#

It would be difficult for a single person to have enough money to license the entire engine, anyway.

sly grove
quaint iris
#

Can somebody recommend me a good dependency injection lib for Unity?

small badge
small badge
royal timber
#

Let me show you the expected result

quaint iris
#

I found Zenject that seems to do all of these things and much more

royal timber
#

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

small badge
royal timber
#

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

small badge
#

(With the first requirement more important than the second.)

royal timber
#

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

small badge
#

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.

royal timber
#

I tried quaternion lookrotation but it never worked as expected, likely from my own incompetence

#

How do I make an up vector then?

small badge
#

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.

royal timber
#

red-blue is a direction, correct?

small badge
#

Yeah, as in subtracting the positions of those two.

royal timber
#

red is the current point, with blue being the previous

#

Let me implement that then

royal timber
#

(I am lerping between n1 and n2, )

small badge
#

How are you generating the red position?

royal timber
#

Through a raycast on the triangle

small badge
#

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.

royal timber
#

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)

royal timber
small badge
#

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?

royal timber
#

Yes

#

moveVector is camera-relative input

small badge
# royal timber

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?

royal timber
#

Oh sorry, I enabled forward-based movement

#

Meaning I move relative to the roll

#

The erratic teleporting was me clicking on the points

small badge
#

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.

royal timber
#

What do you mean the second?

small badge
#

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.

royal timber
#

The points are generated as they should expect

small badge
# royal timber What do you mean the second?

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.

royal timber
#

The main issue here is the roll

royal timber
#

Cross the normal with an Vector3.up?

small badge
royal timber
#

But my vectors aren't up or 0

#

Look at the arrows

#

they are normals, if they were 0 they can't generate

small badge
#

Sure, but that's a screenshot from a frame when it works correctly, right?

royal timber
#

No. Check the video - the normals are always generated perfect

#

they are calculated from the actual triangle edges themselves

#

not from raycasting

small badge
#

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).

royal timber
#

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

small badge
#

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.

royal timber
#

This doesn't happen within the span of a single frame, this is simply just the normals taken wrong

small badge
#

I'm sorry, then I don't understand what problem you're describing any more.

royal timber
#

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

pale pier
#

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

compact ingot
dark cedar
pastel moth
#

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...

devout hare
#

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

pastel moth
pale pier
shrewd thicket
#
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?

forest isle
#
  1. You're not rotating the missile.
  2. the force you'r adding is probably tiny.
pastel moth
# devout hare The boss waves are at `a * n / b` where `a` is the total amount of waves, `n` is...

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?

devout hare
#

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)

wise barn
#

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

pastel moth
devout hare
#

Surely that's the easiest part

#

if current level == total number of levels, then it's the final boss level

pastel moth
devout hare
#

yup

pastel moth
wise barn
#
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.

devout hare
#

yeah, that's the same as my formula but with the terms moved around

pastel moth
#

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

verbal peak
#

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 πŸ™‚

hushed fable
verbal peak
#

@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

hushed fable
#

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.

verbal peak
#

Cool, thanks for the clarification, that makes sense

mild quiver
#

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?

frozen imp
#

@mild quiver Don't cross-post, and not a code question.

mild quiver
hearty merlin
#

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

untold moth
hearty merlin
#

It is the same script that is in the roll a ball project on the asset store

untold moth
hearty merlin
#

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

forest fjord
#
        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...

lime plover
#

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:```

  1. Giving the AI basic knowledge once he gets spawned
  2. Trying things (like that game called Little Alchemy) by fitting different combinations of mechanical parts together.
  3. Testing whatever they make
  4. 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).
  5. 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?

devout hare
#

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

lime plover
#

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

static patrol
#

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.

lime plover
#

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

broken basin
#

You could design your loss function to account for that

lime plover
#

I mean the inventing things part

lime plover
#

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?

broken basin
#

Like, at first I know what you mean by simulating electricity and physics, but the next part is just bizarre

lime plover
#

Yea I know, what I'm trying to say is a bit unclear

#

xD

broken basin
#

It seems that you want an already abstracted and gameified world, yet you want some elements of it to obey the laws of physics

lime plover
#

ehmm

broken basin
#

I would say, if your entire game world was determined by the laws of physics then it would make sense

lime plover
#

Yeah

broken basin
#

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)

lime plover
#

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

lime plover
#

Fpr example: it would be easier to just use Newton's laws and not general relativity as we aren't dealing with big masses

broken basin
#

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

lime plover
#

...

#

not sure how to respond xD

broken basin
#

there are like 5 * 10^24 H2O molecules in a litre of water

lime plover
#

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

broken basin
#

What do you mean by "not 100% accurate"?

#

you were the one that said "an entire country"

lime plover
#

not 100% accurate to how it would be in real life

broken basin
#

I only know of countries in real life

broken basin
#

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

lime plover
#

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

broken basin
#

I think it would be very hard to create something interesting or useful, but you should try and make a prototype

lime plover
#

Indeed

broken basin
#

You should probably check out Dwarf Fortress

lime plover
#

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

lime plover
#

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

broken basin
#

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

compact ingot
#

most of what you need can be created by a system of utility functions and a simple planning system

broken basin
#

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

compact ingot
#

forget about learning and ML in general, that is a wholly different aspect of AI

compact ingot
#

its just something that makes certain things easier to grasp

broken basin
#

That still has a massive impact

compact ingot
#

i'd not overestimate that

broken basin
#

@lime plover what other games have you made?

broken basin
#

but I do know many have tried

void topaz
#

anyone Used A* path finding Package i need help to set it up

lime plover
#

I always get distracted about other things and just completely abandon those projects

broken basin
#

Well, this is just about the hardest project you could possibly choose

lime plover
#

hahaha

#

but how about doing it in smaller steps

#

the invention part is probably something I'll do later as that's the hardest

broken basin
#

Did that work for your other projects?

lime plover
#

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

broken basin
#

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

lime plover
#

yea

broken basin
#

the thing in this case is that a simple prototype of what you're describing could take years to produce

lime plover
#

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

broken basin
#

Because you want to create an extremely detailed simulation of life and machines, and have autonomous robots learn to intelligently design them lmao

lime plover
#

xD

broken basin
#

Most games have very simple, well known rules and parameters

lime plover
#

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

broken basin
#

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??

lime plover
#

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

broken basin
#

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

lime plover
#

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

kindred tusk
broken basin
#

I think it's like when Lisa accidentally creates a civilisation in that Simpsons episode

lime plover
#

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

void topaz
#

anyone who have used A* path finding need help

tropic lake
#

post your question and whoever can help will do so

void topaz
#

need help in A* path finding i placed the Package and set everything according to a tutorial but it's not working

kindred tusk
void topaz
#

yes

kindred tusk
#

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

void topaz
#

well i didn't get anyhelp from the internet so i thought if anyone here has used it before

kindred tusk
#

Good luck! I haven't used it yet. Planning on picking it up soon

void topaz
#

i need to make a 2D Ai to move in a maze any other solution?

kindred tusk
#

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

void topaz
#

navMash is not for 2D

kindred tusk
#

You can find it on openupm

kindred tusk
void topaz
#

you are using it ?

kindred tusk
#

Yep.

#

Works nicely

#

It's just a fork of the default navmesh package with 2D collider detection

void topaz
#

how to set it up?

kindred tusk
#

@void topaz

void topaz
#

ok i am going to Use it and if i stuck somewhere will contact you

kindred tusk
#

Sure. You know how to add it?

void topaz
#

how?

kindred tusk
#

You can add it to your package.json

#
"com.h8man.2d.navmeshplus": "https://github.com/h8man/NavMeshPlus.git#master"
void topaz
#

yes i do have it

kindred tusk
#

*manifest.json I mean

void topaz
#

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

kindred tusk
#

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

void topaz
#

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

kindred tusk
#

On account of not having used it

#

As I explained

leaden jungle
# void topaz i need to make a 2D Ai to move in a maze any other solution?

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

Get the RTS flow field movement system package from logicandchaos and speed up your game development process. Find this & other AI options on the Unity Asset Store.

gleaming thistle
#

man if only you were here days ago @leaden jungle lol

#

I wound up making a pathfinding script from scratch

raw wind
#
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
tough tulip
raw wind
#

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

south sand
#

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

tough tulip
tough tulip
# raw wind i am using one

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?

coral citrus
#

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:

  1. 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
  2. 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

mental pawn
#

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.

fervent parcel
#

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)"

lime plover
#

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?

compact ingot
# coral citrus Yo, I have a few networking related questions I've been making a game in a JS ...

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.

fervent parcel
austere jewel
#

What Unity version?

lime plover
fervent parcel
#

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

fervent parcel
austere jewel
fervent parcel
#

didnt really want to use editor code in this script

fervent parcel
#

however, I set a value to the Emissions and it is visible

#

omg I wasted so much time on this thanks for the help

austere jewel
#

It's a crappy bug, I have no idea if it's fixed on newer LTS versions

fervent parcel
#

so its just.. temporary lol

#

I will try a different unity version and see if I can replicate I guess

austere jewel
# fervent parcel 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)

fervent parcel
fervent parcel
#

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

austere jewel
#

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

fervent parcel
tough tulip
regal olive
#

hi where can i learn C hashtag

midnight violet
#

google?

fervent parcel
#

that said, I found a way to do it in mono but its a round about way

#

Anyway thx

somber swift
covert osprey
#

does someone know what O(dt⁴) is in the context of velocity verlet ?

stable spear
#

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)

covert osprey
#

ah that makes sense

stable spear
#

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

unkempt nova
#

You can copy/paste symbols, but I think that's it

coral citrus
lime plover
#

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?

flint sage
#

That's what siri and all other AIs try to do

#

It's not as easy as you make it sound

lime plover
#

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?

flint sage
#

It depends

#

They can't know everything

gentle topaz
#

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

lime plover
#

Alright, thanks

wary jungle
#

Hi! I'm using the INK pluguin for flexible dialogue, but when I try to select one choice the story does not continue

coarse jolt
#

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,

sly grove
#

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

coarse jolt
#

sounds like a fair call. I am building myframework as a console app hah.

median cosmos
#

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)

fresh salmon
#

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.

median cosmos
#

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

coral citrus
#

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

compact ingot
coral citrus
#

so you just have it check isClient/isServer in the same function? or is there a superior way?

sly grove
#

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.

flint sage
flint sage
compact ingot
coral citrus
#

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

compact ingot
compact ingot
coral citrus
#

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

#

(?)

compact ingot
#

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.

coral citrus
#

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

compact ingot
#

Components here are usually networkBehaviours that share the same network id

coral citrus
#

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

compact ingot
coral citrus
#

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

sly grove
#

depends on your framework of course (sorry haven't been following the discussion, not sure which you're using)

coral citrus
#

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

compact ingot
#

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

coral citrus
#

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

compact ingot
#

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

coral citrus
#

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

compact ingot
#

neither one will prevent you from completing your project, and neither one is perfect

coral citrus
#

right right

compact ingot
#

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

coral citrus
#

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

compact ingot
#

thats easily possible if its not a competitive shooter with mirror and netcode... so long as you understand what the general networking pitfalls are

coral citrus
#

yeah, nothing complicated, just a topdown 2d tile based game

#

so it's pretty ideal for shortcuts like chunking and etc.

#

lmao

compact ingot
#

great

coral citrus
#

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

compact ingot
#

tbh i have come to really detest thick libraries/frameworks, they end up standing in the way more than they help

coral citrus
#

same

compact ingot
#

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

coral citrus
#

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

compact ingot
#

if you worry about GC, you can have a lively debate on the Mirror discord

coral citrus
#

LOL

compact ingot
#

mirror doesn't try to be zero-alloc

coral citrus
#

yeah okay that helps my decision, lmao

compact ingot
#

netcode largely does

coral citrus
#

literally

#

90% of the lag i experience issues with atm on my existing game code

#

is gc

compact ingot
#

in netcode you can't send variable length strings for example

sly grove
#

Photon Fusion is zero allocation

compact ingot
#

really all 'advanced" netcode libraries MUST be zero-alloc

coral citrus
#

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

compact ingot
#

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.

coral citrus
#

wow, holy hell, yeah this makes a big difference

#

hahahaha

compact ingot
#

i wasted so much time before i wondered if there was a better way...

coral citrus
#

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

compact ingot
#

thats where it gets annoying

coral citrus
#

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

compact ingot
#

then you have no separation

coral citrus
#

right...

#

hmm

#

I could not remove the components and just disable them instead

#

and call them that way

compact ingot
#

but in any case, you have to have that rpc component available on both, server and client

coral citrus
#

right

compact ingot
#

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

coral citrus
#

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

compact ingot
amber kite
#

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

hollow wing
#

interesting, ty

untold moth
pulsar isle
#

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.

mint sleet
#

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.

small badge
#

If it's not private you can just look at it. If it is private then no, inheriting classes can't read its value.

austere jewel
#

it seems very excessive to use a switch statement on a boolean

#

just use an if statement

mint sleet
#

I like switch case looks cool

#

πŸ™‚

mint sleet
somber swift
#

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

compact ingot
somber swift
#

I just meant it's completely useless and more unclear to use switch case on boolean than if else

lucid girder
#
public virtual bool OpenClose()
{
  isOpen ? layerPanelAnimation.DoRestart() : layerPanelAnimation.DOPlayBackwards();
  isOpen = !isOpen;
  return isOpen;
}
rugged wagon
#

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

rugged wagon
#
foreach (InputControl con in device.allControls)

thanks πŸ™‚

deep tide
#

hey

amber kite
untold moth
#

I'd guess that it removes all of the mesh data.

amber kite
#

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

fervent parcel
#

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

untold moth
amber kite
#

@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.

untold moth
amber kite
#

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.

untold moth
amber kite
#

I'll poke about, if I find anything I'll let you know πŸ™‚

#

Thanks for your input

regal olive
#

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;
    }
}
misty glade
#

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);
regal olive
#

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.

regal olive
misty glade
#

you'll need it to ExecuteInEditMode if you want to use it in edit mode πŸ™‚

misty glade
misty glade
#

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

regal olive
#

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)

regal olive
misty glade
#

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

regal olive
#

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

sly grove
#

This only works when you create the asset via the Assets -> Create menu.

regal olive