#archived-code-general

1 messages · Page 205 of 1

leaden ice
#

you could also probably just use OpenSteer as a plugin in Unity without reimplementing it though

atomic sinew
#

This part works. If I comment line 66 out, the messenger spits out a lot of gibberish.

craggy totem
sweet raft
#

Might make sense in context. I have a time stamp of when players login and logout. I compare the two, and if enough time has elapsed, the player is granted an item. The amount of time is ever 2 hours. I have that part solved.

The part I'm struggling with is finding out how much time there is (in seconds) until the next 2 hour mark, since that's where the game will start ticking from.

For example if 6 hours and 58 minutes have passed since their last login, they're granted 3 items (one for every 2 hours)...and there's 1 hour and 2 minutes (3,720 seconds) left until their next reward. The game will start ticking up from 3,720 until it reaches 7,200.

So I have the total time in seconds since the last login, which I converted to minutes. I use those minutes to figure out the rest.

double timeSinceLastLogin = (DateTime.Now - new DateTime(playerData.timeOfLastLogin)).TotalSeconds;
int minutesSinceLastLogin = Mathf.FloorToInt((float)timeSinceLastLogin / 60);
int hoursSinceLastLogin = Mathf.FloorToInt(minutesSinceLastLogin / 60);

if (hoursSinceLastLogin >= 2)
    GiveReward(Mathf.FloorToInt(hoursSinceLastLogin / 2));

//CALCULATE REMAINING TIME BY DIVIDING minutesSinceLastLogin by 60...THIS WILL BE X
//TAKE THE VALUE AFTER THE DECIMAL OF X AND MULTIPLY IT BY 60...THIS WILL BE Y
//TAKE THE VALUE AFTER THE DECIMAL OF Y AND SUBTRACT IT FROM 60...THIS WILL BE remainingMinutes
//MULTIPLY remainingMinutes BY 60...THIS WILL BE remainingSeconds

float remainingMinutes = ???
float remainingSeconds = ???

gameManager.SetRewardTicker(remainingSeconds);

Unless I'm making this too complicated and there's a simpler way to go about it...

craggy totem
lean sail
leaden ice
sweet raft
leaden ice
#

why not just store it directly as number of seconds then

#

why do you need a separate field for minutes and seconds

#

also I don't really see how this relates to your earlier question, it seems very different.

#

5 / 60 gives you 5 minutes remaining not 833 minutes remaining

atomic sinew
atomic sinew
#

kinda weird though, because shouldn't it be the exact same? 🤔

leaden ice
#
double secondsSinceLastLogin = (DateTime.Now - new DateTime(playerData.timeOfLastLogin)).TotalSeconds;
double rewardCount = secondsSinceLastLogin / rewardInterval; // for example if 225 seconds since last login and reward interval is 50, you get 4.5 here
long wholeNumberOfRewards = (long)rewardCount; // rewardCount will be 4 here
double fractionalRewards = rewardCount - wholeNumberOfRewards; // fractional rewards will be .5 here
double secondsUntilNextReward = rewardInterval - (fractionalRewards * rewardInterval); // secondsUntilNextReward will be 25 here

Is this helpful @sweet raft ?

lean sail
atomic sinew
#

@lean sail I'm using FMOD as audio middleware. It's pretty powerful 🙂

cyan rapids
#

Hi I was directed to this video but after implimenting the code in the ss i recieve the errors i have ss below too, can anyone help? thankyou

leaden ice
#

also your IDE is not configured

#

You must configure it before continuing

#

!ide

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

cyan rapids
#

sorry whats configuring it and what difference does it make?

leaden ice
#

Hence:

If your IDE is not autocompleting code
or underlining errors, please configure it:

heady iris
#

you will be able to see exactly where the problem is

cyan rapids
#

Ive fixed the errors to code its now just the method to bool error, any idea?

leaden ice
#

first configure your IDE

heady iris
#

Configure your IDE correctly.

leaden ice
#

then, stop making copying errors from the tutorial code

cyan rapids
#

what copying errors have i made, i cant spot none and i am doing the ide im just new im not being funny

leaden ice
#

Line 84, column 35

#

double check it

#

you copied it incorrectly

heady iris
#

Configuring your code editor correctly would make it highlight the exact error...

leaden ice
#

based on the error - you forgot a () around there

sweet raft
cyan rapids
#

idk why u keep mentioning this @heady iris , as i have said im new and not really known with ide and all this stuff as i said i am currently configuring it you dont need to repeat yourself. blue was helping great you didnt need to just repeat what he was saying

heady iris
#

well, you repeatedly ignored our instructions, so we repeated them.

heady iris
# tawny elk

you never said that you are following the instructions. you just kept asking us what the problem was with your code.

#

If you are currently following those steps, that's good. Do that.

cyan rapids
#

just whilst it was being done i just asked if blue knew the fix whilst the config is being sorted

heady iris
rigid island
#

@cyan rapids its also a requirement to get code help on this discord

spring creek
rigid island
#

lol dont mind it, you should see the attitude I got when asked for a video that wasnt shaking from a phone

cyan rapids
#

I just think its a little rude ive clearly stated im new, if im in the wrong place simply redirect me and that was all that was needed. The shakey phone wasnt really greeted by asking for a obs vid it was just greeted by a link to obs and no explaination as to why, if youd explained you couldnt see it properly from the beginning id have used obs as i did once you explained, then i was fine with everyone trying my best to understand a new software, im not attempting to come across as a fool im just looking for help from people who can help me get better

heady iris
#

Have you configured your code editor? We aren't going to get anywhere until you do that.

cyan rapids
#

Yes that is what I am doing

spring creek
dusky lake
#

Hey, have a perspective/math question

I have a cube that im rotating with my gamepads right stick with this line:

        transform.rotation *= Quaternion.Euler(new Vector3(m_RotationVelocity.y, -m_RotationVelocity.x, 0) * (Time.deltaTime * 50f));```
But instead of rotating it based on how its currently rotated i want to always have it spin in the direction of the stick relative to the camera, I know there should be a transform function for that in the camera scripts but tbh my brain is fried rn and I can't figure it out 😄 thanks for any help upfront
#
        transform.RotateAround(transform.position, new Vector3(m_RotationVelocity.y, -m_RotationVelocity.x, 0), 1 * Time.deltaTime * 50f);

Kinda works but its not really optimal i guess as it normalizes my rotation vector

cyan rapids
#

Hi if you need to send me somewhere else for this its fine i get its not really an issue for in here i just thought whoever directed me to do the config could help out, its showing this message everytime i load vs code although ive clicked the link and downloaded it and reset vs. any ideas?

dusky lake
heady iris
cyan rapids
#

i dowloaded the c sharp dev kit from microsoft and yes when clicking get sdk and dowloading and resetting it it just shows the same error

heady iris
cyan rapids
#

nono sorry i was saying i just dowloaded the dev kit, im assuming download that

spring creek
#

But yeah. Get that extension first, it is crucial

heady iris
#

The instructions tell you to install the "Unity for Visual Studio Code" extension. You need to install it.

cyan rapids
#

Sorry just double checking, which is it?

heady iris
#

ah, it just shows up as "Unity"

cyan rapids
#

thankyou

heady iris
#

that will install all of the needed packages

#

One of those packages is the ".NET Runtime Install Tool", which is supposed to handle downloading the software you need

cyan rapids
#

it is now dowloaded but still showing the net core error, is this normal or a worry

heady iris
#

You should restart your computer and then check again.

#

VSCode might be stuck thinking it has no way to get the SDK

spring creek
#

I find that often happens when installing the sdk. The PATH needs to be updated and that can either be done manually, which is a whole thing, or just restart

heady iris
#

it keeps trying to redownload the SDK while I'm on airplanes

#

very annoying

cyan rapids
#

Just restarting anyway, also i apologise for earlier I wasn’t intending on being rude in any way if that is how I come across it’s just been a stressful curveball trying to get used to new software, sorry if I’ve accidentally come here and taken that out on any of you I just rlly need some help with the parts im rlly struggling with

heady iris
#

It's alright (:

spring creek
#

Might be another issue for the bool actually, because that is a different line

cyan rapids
#

Yes figured that out whilst waiting thankyiu, the next rrror is a bool error

#

Cannot convert from method group to bool

spring creek
#

Like Praetor said, might just be missing a ()

cyan rapids
#

It’s saying 35 although there isn’t any code there?

leaden ice
#
  1. Save your code
  2. Check the new error message(s)
  3. share the code and the full error message(s) here
spring creek
#

And COLUMN 35

cyan rapids
spring creek
#

Yeah, need to put IsGrounded()

#

Not just IsGrounded

Praetor called it

cyan rapids
#

so line 35 is safe? sorry i thought it meant 35 and 84 🙂

spring creek
cyan rapids
#

ohhh thankyou that makes sense

#

@spring creek im so sorry to be asking again, but when playing its just as though im constantly jumping on the ground and showing the error - NullReferenceException: Object reference not set to an instance of an object. Any Idea?

cosmic rain
cyan rapids
#

yeah no worries ive said before if they need me to switch chanels i can do theyve just been helping me out in here hence asking in here just because they already know half the issue and helping me thru it

cosmic rain
#

Anyways, learning to handle such simple errors on your own is something you'll need to do at some point anyways, so I suggest you get familiar with the debugging procedure that I mentioned.

#

Feel free to ask for details on each step of it.

cyan rapids
#

is it a simple error ? i didnt know if it was bad or not hence asking just in case, although how do i go about debugging this as the code is fine but the error appears in game so i dont know which line of code is playing up, thankyou

cosmic rain
broken light
#

is it possible to create gameobjects inside a scriptable object but not have it load into the scene? Im trying to create a prefab from code which will be saved in the scriptable object and then instantiate that into the scene later - any attempt to make a gameobject it spawns in the scene which is a pain

cosmic rain
cosmic rain
broken light
#

yeh im trying to find the right api for it

cyan rapids
#

to be honest im just following the video given above to improve my ground detector for a singular jump, the 114 is the new code ill send now

cyan rapids
#

my only guess is thr boxcast is an issue, but the video said it should just work off the bat so i havent done anything with it

broken light
#

i tried that but apparently doesnt work for gameobjects, and prefab utility is for making prefabs which is fine but since im making generated meshes prefab utility doesnt save the meshes so its confusing how people save procedrually generated content in editor cant find many articles on it

crisp bronze
#

Is there a way to create a load screen WITHOUT using LoadSceneAsync? That method just...causes way too many issues

broken light
#

for any async method theres a non async version

cosmic rain
cosmic rain
cyan rapids
#

Ive fixed the error but now the character is always playing the jump animation with nomerrors in game, does this mean it has nothing to do with the code so i will look elsewhere to fix this?

broken light
# cosmic rain If it's just a mesh, you don't need a gameObject for it. But yeah, it seems lik...

if it helps this is the general idea im trying to do :

    public class TankAsset : ScriptableObject
    {
        GameObject _tankObject;

        public GameObject Create(Transform parent = null) => Instantiate(_tankObject, parent);

        //On inspector values change:
        //delete previous meshes
        //create the procedural meshes and save them all as assets to asset database
        //then
        //create prefab assign meshes to relevant created child gameobjects of prefab, save prefab and link to _tankObject
    }
#

im trying to avoid any of that ending up in scene

crisp bronze
cosmic rain
broken light
#

async allows you to do other things whilst its loading so you can determine progress

#

async isn't that difficult to use once you understand the api for async stuff

cosmic rain
broken light
#

i can make temporary scenes?

#

didnt realise that

cosmic rain
#

Yeah, should be pretty easy with the scene manager.

crisp bronze
#

Like the component and gameobject is there

#

it just doesn't render until I manually adjust the color of the Image

#

The issue only appears when using LoadSceneAsync

cosmic rain
#

Maybe even a video demonstrating the issue.

#

I don't know if you're saying something, since I can't enable sound at the moment, so I might be misunderstanding something.

But here's one thing that bothers me: is the loading animation inside the scene that is supposed to be unloaded?

ornate hare
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControllerX : MonoBehaviour
{
public float speed = 20f;
public float rotationSpeed = 45.0f;
public float verticalInput;
public float horizontalInput;
public float forwardInput;

void FixedUpdate()
{
    // get the user's vertical input
    verticalInput = Input.GetAxis("Vertical");
    horizontalInput = Input.GetAxis("Horizontal");

    // move the plane forward at a constant rate
    transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
    transform.Translate (Vector3.right  * Time.deltaTime * speed * horizontalInput);

    // tilt the plane up/down based on up/down arrow keys
    transform.Rotate(Vector3.right, rotationSpeed * verticalInput* Time.deltaTime);
    transform.Rotate(Vector3.back, rotationSpeed * horizontalInput * Time.deltaTime);

}

}
this is my script i am the plane programming challege in unity learn

cosmic rain
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

ornate hare
cyan rapids
#

@cosmic rain figured out my issue is this line of code as the grounded line used to be isjumping so before i was saying when jumping play animation and now im saying when grounded play animation. What code can i add here to make it the opposite?

cosmic rain
crisp bronze
#

I don t know if you re saying something

cosmic rain
ornate hare
#

i think i am overthink the math an bit

#

in the plane challege or at least i am make more diffuclt for myself

cyan rapids
#

doesnt matter

cosmic rain
cyan rapids
#

It worked 🙂

ornate hare
#

@cosmic rain your game is interesting i like it

cosmic rain
#

Where do you have the PlayerRunState type defined?

spring creek
#

Show it

cosmic rain
#

Where is it located in your project?

#

Are they in the same assembly?

unreal ingot
#

is there a Material.SetTextureOffset for rotating a material? I cant find anything on the material methods page for rotating a material around a point

broken light
#

how might i create a unique asset name for a scriptable object via code so it always relates to that scriptable object instance?

#

trying to avoid accidental collisions

cosmic rain
#

Then there's some crucial info were missing.
Can you confirm that the files actually exist in the unity project window and contain the correct code?

broken light
#

would this be a valid one:
AssetDatabase.AssetPathExists("Assets/Tanks/" + this.GetInstanceID() + ".asset");

#

i presume instance id is always unique and unchanging?

cosmic rain
broken light
#

oh hmm

cosmic rain
#

Okay. Does the error appear in unity console too or only in the ide?

cosmic rain
broken light
#

so how do people maintain a link ?

#

safely

#

i cant use something like string name because if i change the name the link is lost

cosmic rain
#

By keeping the meta file safe I guess.

broken light
#

what about GetHashCode

#

although that might have collisions too i guess

cosmic rain
#

Yeah, a hash might have collisions.
The metadata is part of the project. Losing it is kind of like loosing one of the code files, so it shouldn't happen normally.

broken light
#

fair enough i guess its the best option i got

#

so this seems to give an error that the value cannot be null:

void Load()
{
    //if not exist create it
    if (!AssetDatabase.AssetPathExists(_assetPath + GetInstanceID() + ".asset"))
        AssetDatabase.CreateAsset(new Object(), _assetPath + GetInstanceID() + ".asset");

    _asset = AssetDatabase.LoadAssetAtPath<Object>(_assetPath + GetInstanceID() + ".asset");
}

trying to create a container that all my generated stuff will be saved to

#

it doesn't seem to like new Object()

cosmic rain
#

I don't think you can create an Object via constructor.

broken light
#

so if im generating say 10 meshes i want to save this to one asset file

#

how would i make the container for it

#

end result being :

Asset¬
mesh1
mesh2

etc

cosmic rain
#

Hmm... In the docs they use an instance of an SO as a base. And you can create one with ScriptableObject.CreateInstance<Type>()

broken light
#

but isnt the scriptable object already instanced if im generating from a scriptable object's data

cosmic rain
broken light
#

wouldnt this already be an instance? so making an asset inside it based on itself would be kinda confusing no ?

#

or is this not considered an asset

quartz folio
#

Instance ID is not what you want, no? Instance ID is unique to an instance, not to an asset

#

if you want an asset ID then you use the GUID

broken light
#

scriptable objects dont have guids do they?

cosmic rain
quartz folio
#

It's unclear what you're trying to do with this ID

broken light
#

maintain a link to the scriptable object instance

#

so i create a scriptable object file and this has a function procedurally generate meshes which i now need to save them as assets linked to this SO instance

quartz folio
#

I don't really understand what you're doing. If you want to create assets with unique names, use the assetdatabase function that does that

broken light
#

so my scriptable object has data about a room layout. my editor script has a button to generate the meshes procedurally now im trying to save these meshes as assets specifically linked to this scriptable object

#

thats the general idea

#

this is all editor side - the SO will have a gameobject reference i will instantiate at run time later on

quartz folio
broken light
#

so i can just add it directly to the SO ?

#

i presumed for AddObject i first need to create a container asset file to add the meshes to

quartz folio
#

Yes, but isn't that your SO?

broken light
#

is an SO considered an asset in the asset database?

#

wasn't really sure how unity stores them

quartz folio
#

If it's in the project view then it's an asset

broken light
#

oh

#

ill try that then

#

can i save prefabs to it aswell with prefab utility?

#

or do they have to be seperate

quartz folio
#

Note: You can not add GameObjects; use PrefabUtility instead.

broken light
#

right i see

#

its a little bit confusing because they seem to differentiate prefab asset to gameobject even though its same type so when assigning to a field of gameobject it gives mismatch type error

#

im loading it like this:

//[SerialisedField] GameObject
_prefab = PrefabUtility.LoadPrefabContents(_uniquePath + ".prefab");

it says it returns a GameObject type so i'm a bit lost why that won't work

#

if i double click the field it shows the object inspector 🤔

quartz folio
#

Your code doesn't really show the full picture. Perhaps you should move to #↕️┃editor-extensions and post what's drawing that field

broken light
#

sure

thick socket
#

guessing this is a code fix....

#

I have a blue collider and a red collider that have just enough gap that my player gets "stuck" where the red/blue meet when trying to just walk( edit: stuck meaning I cant move right)

#

how might I fix that?

#

(can't make same collider because platform vs wall)

#

atm both using tilemap collider2d with a composite collider2d

#

I imagine trying to do some sort of raycast check is a bit overkill and there is something easier to do

muted idol
#

Guys I just upgraded my TextMeshPro to version 3.2.0-pre.6 but I got this error Library\PackageCache\com.unity.textmeshpro@3.2.0-pre.6\Scripts\Editor\TMPro_CreateObjectMenu.cs(339,31): error CS0117: 'Object' does not contain a definition for 'FindFirstObjectByType'. And when I checked inside the script that line and many other lines is white color. Definitely there's something wrong here but I just have no clue.

dry iron
thick socket
dry iron
thick socket
#

essentially blue platform is a tiny bit off of the red for height so player "catches" on the red one

#

I use tilemap collider + composite collider2d as I dont wanna do it manually for everything

dry iron
thick socket
#

Interesting

dry iron
#

Or of course you could just add a box. Collider right where the two parts meet to even it out. But that may not be the best idea

thick socket
#

Would probably still prefer some sort of approach that wont get me stuck if colliders arent exactly perfect

dry iron
#

Are using a sprite sheet?

thick socket
#

Im waiting for option3, naturally go over bumps without getting stuck 😄

dry iron
#

So you're waiting for your Sprite guy to fix the sprite?

thick socket
#

Im sure there is a code approach Ill try and come up with tomorrow if no one has any ideas/code to share before then

#

Was guessing others have had issue and fixed it in code

dry iron
#

Well you could do a clipping code. Kind of like CS:GO and stairs

#

I haven't done that before so I don't have much experience but you could probably find something online

thick socket
#

Maybe Ill just do what that popular platformer game did...blanking on the name rn

#

Dont remember if it was celest or hollowknight

#

Dont like how many raycasts that will probably use though...at least if I have to use the approach on enemies also

fading halo
#

Does anyone know why these two functions return different values with the same inputs?
C#:

float SimpleRNG(int iteration, float seed, float min, float max) {
    float value = Mathf.Sin((float)iteration * 12 + seed * 78) * 43758;
    value -= Mathf.Floor(value);
    return value * (max - min) + min;
}

HLSL:

float SimpleRNG(int iteration, float seed, float min, float max)
{
    float value = sin((float) iteration * 12 + seed * 78) * 43758;
    value -= floor(value);
    return value * (max - min) + min;
}
fading halo
#

Eh, guess I can just make my own sin function then

fading halo
fading halo
dry iron
#

and mathf = math(float) so it uses floats

fading halo
#

So, you can observe the floating balls here with a very deterministic and ugly value for the wave angle:
i * -40 + (i % 2) * 12 + i * 5 * modAmp;

#

I guess the difference might be decimal, if so, it's like an offset or something. But it gets extremer with just a bit more amplitude. You'd think it wouldn't be noticable on the ships, but it really is O:o

dry iron
fading halo
#

Hm... Can we debug.log, or whatever log they have HLSL, I mean, I'll just check, should be possible

dry iron
#

might be print

lean sail
#

the values u are using are large, so a decimal difference might be major

dry iron
#

you could try rounding the numbers

fading halo
#

Indeed, but, I'll actually start with just making a sin function

#

Or, I'll let GPT do it, not gonna waste time on triviality lol

lean sail
#

I would start by checking each line, like see if its the first line giving you the error. if it is, then break it up and maybe try without sin, see if its still an error

fading halo
#

Genius...

using System;

public class MathFunctions
{
    public double Sin(double angleInRadians)
    {
        return Math.Sin(angleInRadians);
    }
}
dry iron
#

LOL

dry iron
fading halo
#

I realize now that the formula for how to calculate sin is not what I remember. So I can't even verify easily if this is accurate xD

public static double Sin(double x)
    {
        double result = 0.0;
        double term = x;
        int n = 1;

        for (int i = 0; i < MaxIterations; i++)
        {
            result += term;

            // Compute the next term
            n += 2;
            term = -term * x * x / (n * (n - 1));
        }

        return result;
    }
lean sail
#

this looks like a series to me

fervent furnace
#

Taylor series

lean sail
#

I believe its an approximation

fading halo
lean sail
#

ah yea, i fell asleep during that lecture and never learned taylor series 😂

fading halo
#

I mean, I should know... But eh... it's like 4 years ago at this point, and I've been struggling to forget most of it xD

#

I don't care if it's actually sin or that though, as long as it is consistent between the two languages and works with a seed

fading halo
#

Hm... I coulod try using Math.Sin actually... Don't know what will happen with float double conversions, or if it's way more costly or something, but worth to try

#

Ye, nope, same. I'll try the Taylor series

#

Aight, he fixed it
HLSL:

    state ^= (state << 13);
    state ^= (state >> 17);
    state ^= (state << 5);
    return state;
}

float CustomSimpleRNG(int iteration, float seed, float min, float max) {
    uint state = (uint)(iteration * 74755 + seed * 65933);
    uint randomInt = Xorshift(state);
    float value = (float)randomInt / 4294967295.0; // Equivalent to uint.MaxValue in C#
    return value * (max - min) + min;
}

C#:

uint Xorshift(uint state) {
    state ^= (state << 13);
    state ^= (state >> 17);
    state ^= (state << 5);
    return state;
}

float CustomSimpleRNG(int iteration, float seed, float min, float max) {
    uint state = (uint)(iteration * 74755 + seed * 65933); // Some arbitrary prime numbers for better distribution
    uint randomInt = Xorshift(state);
    float value = (float)randomInt / uint.MaxValue; // Normalize to [0,1)
    return value * (max - min) + min;
}

These return consistent values and the seed does randomize so I guess it should be good, no issues so far at least

wild nebula
#

Hello, if I were to have a class that are non-monobehaviour (System.Object), and add them to a list myNonMonoList.Add(new MyNonMonoClass(someParam)), will simply removing them from the list cleans it up properly without any leaks?

full sonnet
#

how do i make a configurable joint set its target rotation to face a point?

somber nacelle
wild nebula
somber nacelle
#

in a nutshell, it's when other objects are no longer referencing it. of course there's some nuance, for example two objects that reference each other but are not being referenced by other objects are not reachable from the root because nothing references them except each other so they would be GC'd

wild nebula
#

So in this case, it will be GCed since the mono with the list of object no longer have it referenced (Removed from list)?

Actually please teach me how to dispose them properly without any GC!

#

Sounds dangerous and non-performant leaving it to the GC

knotty sun
somber nacelle
#

memory management is a pretty large topic tbh. you're better off reading some articles/books about it than attempting to get comprehensive info in discord about it. but for classes and stuff, unless they are touching native objects you typically don't need to worry about disposing them manually. and if you did need to you'd use something like the IDisposable interface to clean up what you've done.
but in your case here simply letting the GC handle it is likely 100% enough.

and yes, if nothing else in your game has a reference to the object in the list then it will be GC'd some time after it has been removed from the list (since the list will no longer be referencing it)

wild nebula
#
public SomeClass : IDisposable
{
    // Do I call this manually whenever its no longer needed?
    public void Dispose() 
    {
        // What goes in here?
    }
}
knotty sun
#

read the docs

patent hound
#

Odd question, I work with a team as a programmer and want to create a few booleans that are public so the level designers can set them, but some of them are mutually exclusive

#

Is there a way to make them into a radio select in the editor so the level editors don't accidentally choose two that conflict?

somber nacelle
#

you sure you want a bool and not perhaps an enum?

#

otherwise you'd probably need some custom editor scripting for that

patent hound
#

Hmmmst alright, an enum wouldn't make sense in this situation, I'll just make sure the tool tips have all caps on the fields lol

#

And of course I'll make sure to add sanity checking

lean sail
#

Thatd be a quick way, probably not best

#

Oh thatd probably be annoying in some cases actually

patent hound
#

Yeah I think im just gonna have to sanity check ghe input in some way and put big capital letters in the serializefield tooltips

heavy thorn
#

I'm attempting to generate single frames and draw them to a texture at a specific frame rate, what would be the most efficient approach to update the texture?
My current approach is to create a new texture @ each frame using LoadRawTextureData and my frame data as byte array and use this texture on a material

pliant mulch
#

someone is experienced in rts terrain generation and performace? I like to talk about this argument

vague tundra
#

Hey guys.
I have a 2D project. I am trying to get lighting and shadow casting working.
With my walls here, I initially scaled them to increase their size, however this was stretching the sprite no matter what I did.
I need the sprites to tile, so I have instead moved what was my scale to the sprite's size, which allows the wall to be visually larger and the sprite to tile.
However, the issue I've come across now is that the shadows are functioning as if the sprite is still 1x1.
My desired result is to have the whole wall be "solid" such that the shadows are cast as expected. The sprite tiling needs to be maintained.

shadow flume
#

Hey, one of my beta testers is having trouble to run our game. He is getting this error after the map (scene) was loaded

d3d11: failed to create buffer (target 0x50 mode 0 size 720000) [0x8007000E]

His HW config from the player.log is

GfxDevice: creating device client; threaded=1; jobified=1
Direct3D:
Version: Direct3D 11.0 [level 11.1]
Renderer: AMD Radeon RX 5700 XT (ID=0x731f)
Vendor: ATI
VRAM: 8151 MB
Driver: 31.0.22011.4008

Any help is greatly appreciated on this matter! Thank you!

#

The Unity version is: Initialize engine version: 2021.3.23f1 (213b516bf396)

#

The menu before the game level is working and the error only happens after loading the level.

cosmic rain
#

They might be able to see what uses how much memory in the task manager.

thick socket
#

Not sure a good code fix without many raycasts

cosmic rain
#

Sorry. No clue. Don't do much 2d.

#

Maybe think of how not to arrive at that situation(with overlapping colliders) instead.

thick socket
#

I was thinking it was caused because 1 collider was just a tiny bit taller than the other and it wasnt an overlapping issue

#

Ill un-overlap that part and see 🙂

cosmic rain
#

When you say that your character is stuck, do you mean like it's dead locked and can't move in any direction?

#

Or just to the right?

thick socket
#

Just the right

cosmic rain
#

Ah, okay. Are you using a box collider for the character?

thick socket
#

Capsule collider I thought...maybe I didnt change that though so it might be box

#

(Turning on pc rn)

cosmic rain
#

Might want to confirm that, as such issues are common with boxes.

spice cypress
#

Hey all, I'm wondering if I encountered a Unity bug? I'm working in 2023.2.0b12 and I'm getting an error:

type is not a enum value
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

It seems the error is coming from an ArticulationBody when I set the Articulation Joint Type to anything but Fixed and specifically, when I'm looking at the articulation body in the inspector. If I click on a different game object and a different inspector shows up, then I stop getting the error. I tried making a new scene and it still happens, I tried making a new game and it happens. Has anyone run into this?

thick socket
#

Gotcha, figured it was an issue with all colliders not just box

#

it was indeed still box collider

#

lemme fix that and try again 🙂

#

yep fixed now thanks!

#

when should I make variables "readonly"?

#

figured private was enough but its suggesting I make a bunch readonly

#
public class WeaponAttack
{
    Bullet bullet;
    MyWeaponType weaponType;
    AttackType attackType;
    Fighter fighter;
    BulletTypes bulletType;
    float projSpeed;

    public WeaponAttack(MyWeaponType weaponType, AttackType attackType, Rigidbody2D FireballPrefab, BulletTypes bulletTypes, float projSpeed = 15f, Fighter fighter = null)
    {
        this.weaponType = weaponType;
        this.attackType = attackType;
        this.projSpeed = projSpeed;
        this.fighter = fighter;
        if (FireballPrefab != null)
        {
            this.bulletType = bulletTypes;
            bullet = FireballPrefab.GetComponent<Bullet>();
        }
    }
#

it suggests I make all of those variables readonly

latent latch
#

it's more that your ide doesn't see you changing the variable outside of the constructor so might as well

thick socket
#

any real reason to actually make it readonly?

#

or just to make the ide happy 😄

latent latch
#

a reminder not to redeclare a list or dictionary which you've already initialized

#

I think you can still append to those lists, but just not invoke new() on it again.

#

There's actually even a stricter readonly list wrapper in c# to prevent you to appending to the list if you ever need that (useful to keep your SOs completely immutable)

heady iris
#

readonly prevents you from assigning to a variable. This doesn't really "do" anything in its own right.

#

as mao said, it has nothing to do with preventing you from mutating the contents of the variable

thick socket
#

so I start in Scene1 and the joystick and jump button work

#

if I start in mainmenu the HideOnPause is disabled, then when I click start it goes to scene1, enables HideOnPause....and all the buttons/joystick stop working (they appear there still though)

#

any idea what might cause that?

#

jumpButton below

#

Floating Joystick code

using UnityEngine.EventSystems;

public class FloatingJoystick : Joystick
{
    protected override void Start()
    {
        base.Start();
        background.gameObject.SetActive(true);
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        background.anchoredPosition = ScreenPointToAnchoredPosition(eventData.position);
        background.gameObject.SetActive(true);
        base.OnPointerDown(eventData);
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        background.gameObject.SetActive(true);
        base.OnPointerUp(eventData);
    }
}
#

I dont see anything that sticks out as an issue, but it confuses me why it works if I start in scene1, but leaving and coming back breaks it

heady iris
#

Did you put this in the DontDestroyOnLoad scene?

thick socket
#

its not a scene...but yeah

heady iris
thick socket
#

hmmm...looks like it might be my SceneUI getting in the way

#

aka UI Document getting in way of Canvas

heady iris
#

that's why it shows up in the hierarchy like that

heady iris
thick socket
#

huh, didn't know it was actually a scene itself

heady iris
#

The order in which the objects are created will be important if there's nothing else to break the tie

#

I guess the order in the hierarchy might also matter. I am less sure about how that works with multiple active scenes, though

thick socket
#
using UnityEngine;

public static class BootStrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
}
#

Given that code isnt actually "on" anything, how does unity know to do it?

#

Does it go through every code file and check for things like that?

heady iris
#

Roughly, yeah.

#

Attributes don't do anything by themselves.

#

They're only ever accessed via reflection.

#

So I'm guessing that it iterates over all assemblies, then over all types in each assembly, then over each member in each assembly, and checks if the attribute exists

#

That's gotta be a little slow lol

#

I wrote code that worked like that once to...search for types with attributes on them. It took a hot second

chilly parcel
#

"If the application uses the WebCamTexture class Unity adds the CAMERA permission to the Android App Manifest and requests permission from the user the first time that the application uses WebCamTexture."
how do I prevent this behaviour? I have a code with WebCamTexture on my assemblies but I don't use it

heady iris
#

is this from third party code that you can't modify?

chilly parcel
#

I can modify, I thought about add a define directive to disable this on quest only

#

I also use this code on android (no quest)

heady iris
#

Since you need to completely remove the code that uses WebCamTexture, #if directives will be the way to go.

chilly parcel
#

I see

#

thanks

livid olive
#

SpawnedBottom.GetComponent<GravityForItem>().enabled = false; Disabling a script in another game object works like this right?

#

GameObject SpawnedBottom = Instantiate(SweetBottoms[Random.Range(0, SweetBottoms.Length)]); Also this is the instatiation of SpawnedBottom

#

There are context to these names i swear 🥹

#

Also do game components rename if you rename a script?

quartz folio
#

If you refactored the code correctly, yes. The connection between the script and the component is made via the GUID that is in the .cs.meta file associated with the .cs file

heady iris
#

That's the vital part. You can rename a file + its meta file -- but not rename the class -- and wind up with a broken component.

But, once you fix the class name, everything goes back to normal.

#

If you just change the file name in Explorer, unity will delete the old .meta file and generate a new one. It will think this is a completely different script asset.

chilly parcel
#

if you rename the class on rider it will automatically rename the meta and the .cs file

#

I think visual studio will do that too if you have the unity plugin (i don't remember exactly)

heady iris
#

yeah, Visual Studio and VSCode can do that too.

#

I usually just do it in Unity anyway because it feels safer :p

chilly parcel
#

safer but slower

#

I mean, not safer

#

lmao

quartz folio
#

I will never do it in Unity because I trust Rider with my life

thick socket
#

I've used that quite often

patent hound
#

So I've got a function that gets called by player input object but unlike the others it seems like it's being called twice every time I press the button, has anyone ever encountered this? Is there an easy way in unity I can check what event is calling a function

ancient whale
#

I can't find the test framework package (com.unity.test-framework) on GitHub anywhere? I want to raise an issue. Anybody able to find it?

heady iris
patent hound
#

The PlayerInput object

heady iris
#

is this the class generated by the new input system?

patent hound
#

For the new input system

heady iris
#

oh, so the component.

patent hound
#

Yes

heady iris
#

Show its inspector.

patent hound
#

Idk why but it's only calling this event weird. It calls it 2 times on press and one on release, the other ~15 controls are fine

#

Give me a sec I'm restarting the editor to make sure it's not a weird bug

#

Yep it isn't a unity bug, still the same 3 call behavior, I also commented out the entire function and replaced it with a single debug.log to confirm

heady iris
#

Please show me the inspector for the player input component.

patent hound
#

here is the inputs inspector, the select grenade input is the only one that is acting up, the function is being called 3 times

#

here is the binding, nothing strange here

heady iris
#

Change the target of Select Grenade to something else. See if the EquipNextThrowable method is still being called.

patent hound
#

and here are the properties for the playerinput component

heady iris
#

(and see if the new target is now getting called multiple times)

patent hound
#

It's calling the new function 3 times lol

heady iris
#

does this persist if you change the binding to another key?

heady iris
patent hound
#

Yeah I didn't know if unity had a stack trace for the event system, im not new to c# debugging but the unity event and input system is new to me

patent hound
heady iris
#

well, everything will have a stack trace, but that'll just be series of methods that got called

patent hound
#

Clearly it's that player input calling it though because changing the thing it invokes just caused it to invoke that 3 times

#

Changed the binding but it's still calling 3 times, gonna try making a new input and seeing if that works

dusky lake
#

Hmm, I enabled pre-release packages and want to install InputSystem 1.8.0-pre (for the SearchField fix) but it still only shows me the 1.7.0 thats stable, any way to update it?

heady iris
patent hound
#

Made another input added a binding to it and it's calling functions 3 times as well.

dusky lake
heady iris
patent hound
#

Same input action asset, just added another action with a different binding

heady iris
dusky lake
#

Uhh, thanks 😄

heady iris
#

So it should be named com.unity.inputsystem with a version of 1.8.0-pre.1

patent hound
#

It may be calling all the actions 3 times and it's hard to tell because almost all the calls wouldn't be affected or involve ready/animation states

heady iris
#

That is possible. You should check for that.

heady iris
#

oh, you know what

#

I bet you're not checking if the action was performed

#

the methods take a CallbackContext, right

#

that context includes which phase the action is in

#

started, performed, and cancelled will be the relevant ones here

#

If you only care about when the button actually goes down, then you should return if context.performed is false

patent hound
#

Wow I can't believe I have wrote like 24k Lines of code on this project and never knew that because of how my character works lol

#

I just threw in a if(!context.performed) return

normal hedge
#

I am having an issue where I have a list of serialized objects that is serialized and accessible in the Inspector (1)(2), but when I retrieve that list, it contains an extra element which is the null initialized element for that list (3), It does not show up in the Inspector (4), but causes problems down the line.
Why does it exist, and is there a way other then specifically removing it to get rid of it?
This is currently being accessed in the editor using [ExecuteInEditMode].
(1)

    [SerializeField] private List<ConnectionData> connectionsUp = new();
    [SerializeField] private List<ConnectionData> connectionsDown = new();
    [SerializeField] private List<ConnectionData> connectionsRight = new();
    [SerializeField] private List<ConnectionData> connectionsLeft = new();

Ignore that I am using KeyCodes here

public List<ConnectionData> GetOptions(KeyCode direction)
    {
        var list = direction switch
        {
            KeyCode.UpArrow => connectionsUp,
            KeyCode.DownArrow => connectionsDown,
            KeyCode.LeftArrow => connectionsLeft,
            KeyCode.RightArrow => connectionsRight,
            _ => null
        };
        return list;
    }

(2)

[Serializable]
public class ConnectionData
{
    public ConnectionData(Transform connectsTo, float weight)
    {
        this.connectsTo = connectsTo;
        this.weight = weight;
    }

    [SerializeField] public Transform connectsTo;
    [SerializeField] public float weight = 1;

    public override string ToString()
    {
        return connectsTo ? $"{connectsTo.name}:{weight}" : $"null:{weight}";
    }
}

(3) Copy from the Debug Log:
[[AirBorderBL:1,AirBorderBR:1,null:1,WallBorderT:1]]
(4)

weary hound
#

is just doing math in scripts (but a lot of it) not that performance heavy?

heady iris
#

computers are pretty good at math

#

Profile your code if you think there's a performance issue.

weary hound
#

okay

heady iris
#

"AirBorderBL" and "AirBorderBR" aren't anywhere in that screenshot

normal hedge
#

Ok, slight mess up there, but the problem is that all of them have that

#

(more log)

#

I am iterating through all of them, and every single one has that null element

heady iris
#

i would see how an element with no connections at all behaves

#

I'd also see if this null entry corresponds to a specific entry in the list

#

each list contains one thing in this example

#

i wonder if an object is being destroyed and showing up as null here

#

that'd be weird for something that's executing in edit mode, since you'd think the object would...well, stay destroyed

normal hedge
#

funniest is, that null is even there when I get the list in (1) lower

#

found the outliner for this one:
[[AirBorderBL:1,AirBorderBR:1,null:1,WallBorderT:1]]

#

I have no tiles where I have more then 3 connections

heady iris
#

Show how you're creating that log entry

#

actually, just sharing the whole script would be useful

timber kernel
#

Hey does anyone have any guidance on organizing scripts? i have scripts attached to buttons, to prefabs, to scenes, sometimes to empty objects. it's getting disorganized :/

heady iris
#

well, you are going to have components everywhere

normal hedge
heady iris
#

everything in your game is made of GameObjects with components on them

#

you can reduce complexity by making sure you aren't using GetComponent (and its siblings) all over the place.

#

so, prefabs should usually have a single top-level component that has references to other components on the prefab

#

an enemy should have an Enemy component that references its Animator, for example

#

rather than just manually searching for its animator when you need it

heady iris
#

For example, all of your "manager" components can be on objects that are parented to a single "Managers" object

#

I like to put all of the level-related objects under a "Level" object

#

which, surprise surprise, gets a Level component that references important things the level must always have

normal hedge
normal hedge
# heady iris I'll have a look in a lil bit

Oh, additional context that might help understand:
The Goal is to create a wave function collapse - right now I am calculating the entropy (here directly the number of tiles that could spawn at that location) to then actually spawn the tiles, my original tip off was that there are no 3 connections for the "Wall", while it tells me there are 4
(The 0 is wrong as well, but thats another problem)

EDIT: for now I will just workaround by removing all elements that would be problematic.
Would still love to know why/how that happens

ornate hare
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

ornate hare
modern creek
#

I have a DOTween tween that I'm reusing and I'm getting some errors on the following:

        if (_cameraMoveTween != null && _cameraMoveTween.IsPlaying())
        {
            _cameraMoveTween.Kill();
        }

DOTween is reporting that I'm trying to kill an invalid tween. Am I misunderstanding something about IsPlaying()?

#

(do I need to call IsActive() as well in this check?)

thick socket
modern creek
#

For this project, they don't use cinemachine. They control the camera explicitly (not my codebase). 😛

There are some .. conflicts with how they're controlling the camera - they need an OnComplete callback to restore control to the player if they're doing some camera work in a narrative step.. but sometimes the narrative grants reward chests, which also call this method (ie, zoom to another part of the map to grant the reward). I basically need to check if the camera tween is rolling and if so, kill it and tween from that position to the new destination

#

It works fine but......... I'm getting dotween safe mode errors that the tween is invalid unless I check for IsActive as well as null and IsPlaying

#

💀 indeed.. the codebase here on this project is occasionally ... 🫠

cold parrot
#

its best to not kill a tween directly but instead kill the target it runs on or use a handle

swift falcon
#

Is there a way to add UnityEvent as a listener in an UnityEvent?
Like this:

public void UnityEvent one;
public void UnityEvent two;

one.AddListener(two);

I dont want to use unityaction here so

cold parrot
#

FYI if you do this, you are digging yourself into a hole

#

avoid event chaining if possible, it can only make things worse (for debugging/testing)

chilly parcel
#

or one.AddListener(two.Invoke)

dusky lake
#

Wanted to use odin for my newest project, just saw this warning: https://img.sidia.net/ZEyI5/NaVuzErO91.png/raw

Can anybody tell me the consequences if i decide to keep serializer? Can't find good info about it anywhere and well prefabs are a key part of unity..

Only reason i want to use the serializer is to be able to use their enhanced inspector features but if it means my prefabs are bugging its more of a deadweight

polar marten
#

do you have any prototypes or art assets?

warm stratus
#

Hey, is it possible to set padding propreties of a rect mask 2D to a percentage value?

green ruin
#

hey everyone, how would I set up a mouse entered event inside of a script? i need it to be set up during runtime because there's a lot of the same object basically using the same event but it would take a long time to individually set the event in the unity ui for each one

orchid bane
#

Can I somehow restrict the returned types only to those which implement a specific interface?

public interface ITypesWithUuidProvider {
    public IEnumerable<Type> GetTypes();
}```
livid olive
#

Hey all I'm attempting to access a grid array from another class but can't seem to get it. void Update() { gridShare = GetComponent<GravityForItem>().grid; } Instead it tells me that grid cannot be accessed with an instance? How else can i get this data from one class to another?

somber nacelle
#

it sounds like you made grid static

livid olive
somber nacelle
#

then you don't access it through an instance reference. you access it directly through the class

#

just keep in mind that something that is public and static can be modified by any other object at any time

livid olive
#

So like just the class itself?

livid olive
somber nacelle
#

then familiarize yourself with the basics of the language

main coral
#

Hey is there a tutorial how to use new "Unity Player Accounts" for Unity Authentification ?

green ruin
frank totem
#

I'm trying to have a stack where my Unity client is authenticated by my .NET Core server which retrieves auth tokens from Azure AD. Has anyone ever done this before?

swift falcon
#

How can i get the name of declared variable in class?
For instance:

public class X
{
  public void Method()
  {
    // Expected result: "variableName"
    Debug.log(declaredName);
  }
}

public class Y
{
  public X variableName;
}

I want to do this for debugging purposes. I know there is some other people encountered this thing but i actually dont know how would i search this one and i dont want to ask lovely AI's to "How can i search this thing"

somber nacelle
#

you can use the nameof operator to get the name of a variable or method you have access to

swift falcon
somber nacelle
#

or you can use reflection

swift falcon
somber nacelle
swift falcon
#

I searched it but it seems it is not possible

somber nacelle
#

like what is your actual goal here

swift falcon
# somber nacelle well then what is the actual *purpose* of this?

Uh it is weird thing but i'll explain with an example:

public UnityEvent event;
public UnityEvent anotherEvent;

public void Start()
{
  event.AddListener(OnCallback);
}

private void OnCallback()
{
    // Log the variable name to debug better for what is changing instead of logging the type name
    Debug.Log($"{this.GetType().Name}");
    anotherEvent?.Invoke();
}```
somber nacelle
#

that doesn't answer the question

#

and it also doesn't help that you aren't even using a real example

swift falcon
# swift falcon Uh it is weird thing but i'll explain with an example: ```cs public UnityEvent ...

Invoking another event by another event makes the debugging harder. So imagine the event invoked the anotherEvent.Invoke but who did that? "ClassName" did that? We dont know any information where it is came from. If there was a variable name, it would be better. I do know i could use UnityAction or even Action since its same thing but i cant. I could not give another information because it is what im trying to achieve there is no more aim.

somber nacelle
#

so in other words you want to know what event invoked a specific method without that event passing that info along to the method?

dusk apex
swift falcon
somber nacelle
#

weren't you also already advised not to chain events like that for the specific reason that it makes it harder to debug?

swift falcon
somber nacelle
#

best you can probably achieve is getting the current stack trace. that won't necessarily say what event was invoked though

swift falcon
#

Thank you for helping. It seems creating a string variable "propertyName" in the class is the only simplest way to create this illusion. I need to think another way for invoking nested actions sadok or literally get rid of nested things

unreal ingot
#

is there a Material.SetTextureOffset for rotating a material? I cant find anything on the material methods page for rotating a material around a point?

leaden ice
#

Easy enough to make in shader graph

unreal ingot
cosmic rain
#

Sounds more like a job for proper uv mapping.
Are you generating the mesh procedurally?

tawny mountain
#

Is there a channel for ar foundation?

tawny mountain
wraith thunder
#

is it possible to cut a cylinder into the terrain? trying to make a golf hole and failing....

leaden ice
lean sail
ornate hare
loud zenith
#

I'm using Firebase Cloud Messaging in my game. Using that, when a player challenges their friend, their friend will get a push notification from the backend with extra payload data attached to it. In Android this is working fine. But in iOS, I'm getting the push notification but when the app is opened on clicking it, I'm not getting any payload data from the notification.

I have noticed that the event Firebase.Messaging.FirebaseMessaging.MessageReceived is not fired in the game because I have added a log in the event listener which is not printed. What could be the reason? This was working fine when I used Firebase v10.7.0. In this version, I have updated to v11.4.0. I tried upgrading to v11.5.0 but still the issue persists.

somber nacelle
ornate hare
#

No I have not, also I am on unity Learn unit 2

somber nacelle
#

well as you can see from the text in the message box, clicking continue will reimport the assets and stuff for the version of unity you are trying to open the project in

#

also it looks like you're just opening it by double clicking the scene instead of actually adding the project to the hub and opening it that way

grave quarry
#

Tried a few things, ended up doing this. Worked well and I was able to keep the lerp as I wanted. thanks.

native fable
#

Has anyone used ProcessStartInfo and Process.Start to call a console command? There's no way the coding will fail? Because the command in the terminal is executed ok, but not in the code, it throws an error

var keytoolPath = "/Applications/Unity/Hub/Editor/2021.3.0f1/PlaybackEngines/AndroidPlayer/OpenJDK/bin/keytool";
ProcessStartInfo psi = new ProcessStartInfo(keytoolPath, $"-genkey -v -keystore \"{keystorePath}\" -storepass {keystorePassword} -alias {keyAlias} -keypass {keyPassword} -keyalg RSA -keysize 2048 -validity 50 -dname \"{dname}\"");

psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;

using (Process process = Process.Start(psi))
{
    string output = process.StandardOutput.ReadToEnd();
    string errorOutput = process.StandardError.ReadToEnd();

    process.WaitForExit();

    if (process.ExitCode == 0 && File.Exists(keystorePath))
    {
        UnityEngine.Debug.Log("Keystore generated and saved.");
    }
    else
    {
        UnityEngine.Debug.LogError("Failed to generate the keystore. Error Output: " + errorOutput);
        UnityEngine.Debug.Log("Standard Output: " + output);
    }
}
native fable
knotty sun
# native fable macos

I use /bin/bash as the exe and then -c followed by the rest of the command as the arguments

native fable
native fable
cosmic rain
#

Environment variables are passed to the application when it is launched. It could be that unity just discards unnecessary variables.

native fable
knotty sun
knotty sun
native fable
knotty sun
native fable
#
string unityPath = EditorApplication.applicationPath;
string unityContentsDirectory = Path.Combine(unityPath, "Contents");
string jdkPath = Path.Combine(unityContentsDirectory, "PlaybackEngines/AndroidPlayer/OpenJDK");

is this valid for each platforms?

mellow sigil
#

It's not valid in any platform

#

EditorApplication is available only in the editor

#

and nevermind, now that I read the rest of the conversation you're talking about the editor

#

ignore me

native fable
knotty sun
rough sorrel
#

Hi. Does anyone know if OnCollisionEnter works if the collider is in its children and the rigidbody is in its parent please?

rough sorrel
cosmic rain
rough sorrel
#

I'm basically smashing myself into the ground so that should be detected haha

#

wait, does the other collider have to have a rigidbody too?

#

like my code is literally:

void OnCollisionEnter(Collision collision)
        {
            Debug.Log("ouch");
            
        }
#

and the console doesn't ouch

quartz folio
rough sorrel
#

then how can I detect if it is actually doing something?

#
void OnCollisionEnter(Collision collision)
        {
            transform.position += new Vector3(0, 100, 0);
            Debug.Log("ouch");
            
        }

Something like this should tell me if it detected it or still no?

Edit: Nope

quartz folio
#

Sure. Generally better to use your IDE's Debugger and a breakpoint, but that works

rough sorrel
#

still doesn't detect it😅 I might be missing something very basic but idk what

quartz folio
#

Go through the resource I linked

rough sorrel
#

maybe if I create a new script just to test that

rough sorrel
cosmic rain
cosmic rain
quartz folio
rough sorrel
rough sorrel
cosmic rain
rough sorrel
#

it is already on the same gameobject as the rb

#

now I'm going to try a very basic test to see if it even detects something with a simple cube or something

cosmic rain
#

Ok, then it should work. But just to test, try putting it on the object with the collider.

rough sorrel
#

hmm that does seem to work on an empty scene just to test that, but also works when the object is a child

#

idk what's with the other scene then haha

#

I'll experiment

#

okay the issue could have been that I was using a mesh collider for the ground, because I changed it to a box collider and now it kinda works
Edit: Still doesn't seem to work if it isn't in the gameobject with the rigidbody component

cosmic rain
rough sorrel
#

Well basically: The aircraft has a rigidbody, and in its children there are the control surfaces, which have a component that should detect any collision, and that gameobject has a collider on its first child

cosmic rain
#

Is it the object with the rb?

rough sorrel
#

the object with the rb is this one

#

and then this is the object that should detect the collision

#

I might be missing something very basic but idk what exactly that is

rough sorrel
# rough sorrel and then this is the object that should detect the collision

okay so apparently if I add a rigidbody to this GO it sometimes does something, but then I have to move all the logic to the main aircraft gameobject and check for the components of the control surface when it detects a collision...?

Edit: Yeah I will most likely do this because the other option doesn't seem to work and I'm still not sure why but well

cosmic rain
rough sorrel
#

it is on its child

cosmic rain
#

Ok, that's not gonna work. The script needs to be on a gameObject with either an rb or a collider.

rough sorrel
cosmic rain
graceful latch
#

how can i detect what layer i am standing on in a unity 2d top down project?

#

ive been trying different things for like an hour now

cosmic rain
#

Or just a trigger collider.

rough sorrel
rough sorrel
#

wouldn't that end up affecting performance?

cosmic rain
#

To a degree, sure. But there's no better solution.
Characters with Ragdolls or just collision detection can have tens of rbs too. It's normal

#

Since they're kinematic, they're not gonna add much overhead

rough sorrel
#

well yeah if there's no better solution I will have to do that

#

thanks

cosmic rain
rough sorrel
#

oh okay

graceful latch
#

thank you so much

visual jasper
#

how would i put

                        tileClass = tileAtlas.coal;
                    if (ores[1].spreadTexture.GetPixel(x, y).r > 0.5f && height - y > ores[1].maxSpawnHeight)
                        tileClass = tileAtlas.iron;
                    if (ores[2].spreadTexture.GetPixel(x, y).r > 0.5f && height - y > ores[2].maxSpawnHeight)
                        tileClass = tileAtlas.gold;
                    if (ores[3].spreadTexture.GetPixel(x, y).r > 0.5f && height - y > ores[3].maxSpawnHeight)
                        tileClass = tileAtlas.diamond;
                }

into my generation code which is

private Sprite ChooseTileSprite(int y, float maxHeight)
{
    if (y < maxHeight - 1)
    {
        
        return tileAtlas.dirt.tileSprite;
    }
    else
    {
        return tileAtlas.grass.tileSprite;
    }
}
snow kindle
#

hi everyone, someone knows about this error?
"Indexer access returns temporary value. Cannot modify struct member when accessed struct is not classified as a variable"
This l_matrices is a list of structs

still carbon
#

Unity is caching the last resolution explicitly specified for a build via Scene.SetResolution(). How do you clear that - where is that value stored?

frank totem
snow kindle
knotty sun
snow kindle
#

yeah I guess this is working due to I save data into my function before to assign a property from my struct instance

swift falcon
dusky lake
#

Is there a way to tell rider i want a different namespace for x folder?

I like to mark my main working folder with _Name to have it at the top and still want the namespace to be Name.Character or whatever but rider cries about wrong namespace

frank totem
#

@swift falcon Might be a stupid question then: why is it called serverless sql? Is it because we don't need to spin up a vm to host it?

Yes to both of those functionalities. I also want to be able to spin up threads ("lobbies"). Do you think it's wise to do this on the same process as the Web API? I have a feeling it's probably better if the Web API just acts as a "messenger" that tells another server to spin up threads and then returns to the user the ip/port to connect to, but I don't have the full picture in my mind

#

I've also read about load balancers, and aren't too sure where that might fit in this. I'm guessing we could load balance the calls to the Web API, and also balance out the load of these "lobby" servers that spawn and die frequently.

#

I currently have two projects: one for the Web API, and another for the server that spawns the lobbies. I'm thinking of making the second a Web API as well... just cause I'm not sure how else to communicate with it from the first server.

swift falcon
#

On the topic of lobbies, I don't have the experience to offer the best advice. I'm working with Mirror for networking functionality.
Basically, the API could help you know who is authenticated within your game, and have the reference to whichever type of ID you setup for them within your database structure, so that the server could make further calls to update/retreive relevant player data.
But yes, everything on azure can be elastically scaled, geo-redundant, so you can start small and it will scale with you forever as needed.

#

serverless = cloud native = doesn't require a server to be up and running 24-7. it can save costs, and go offline automatically, then spin back up quickly upon a request. this approach can save some $$$ by not having to run the VM 24-7

swift falcon
#

I got two classes. First of them is generic abstract class and its base of the derived classes. Second one is derived from base class.
Looks like this: https://hastebin.com/share/tufapufugo.csharp
I want to automatically call the BaseClass constructor without typing a constructor in DerivedClass.
Base constructor will get called in normal C# but i dont know why it didnt work there. Isn't unity using new() at the background or do i misunderstood the concept?
https://dotnetfiddle.net/9ZSz6m
Do i need to type constructor for all derived classes?

heady iris
#

there's nothing special about plain old C# classes

latent latch
#

You got to call base to* use the previous constructor in c#

swift falcon
#
    {
        public DerivedOne() : base()
        {
            Console.WriteLine("DerivedOne Constructor");
        }
    }```
heady iris
#

note that nothing in your code would actually construct anything

#

the class is not serializable, so unity isn't going to touch it when it looks at an instance of MonoBehaviourClass

unreal notch
#

Hey, could someone give me a hand with my save system here?
currently, in webGL builds, when I use Application.persistentDataPath it generates an 'md5 hash of data path'
but I want my saves to be presistent between versions....

one solution I'm attempting to use is interacting with the browsers local starage through javascript libraries in my games plugin folder, but I'm having a weird issue that I can't find any info on.... that being that the data is being saved, I can view and read the value as the json file, properly formatted in my browsers dev tools, however the key.... is not what I assigned it... it is instead a random string of numbers and I have no idea why or how to fix it, tried for hours

swift falcon
unreal notch
heady iris
#

if a DerivedClass is constructed, then, if you don't give any explicit instructions, the zero-argument constructor of the base class will be invoked

#

are you sure that you are actually constructing a DerivedClass at any point?

rain minnow
unreal notch
#

this is just one of a few solutions, if there is a better/easier to implement solution for making saves persistent between different webGL versions, I'd love to know!

heady iris
#

that's the md5 hash

unreal notch
#

its not

#

this is what I'm seeing

heady iris
#

oh, you're writing to local storage

unreal notch
#

the keys are just... random and not the string I assigned in my code

tawny yacht
#

Is there a better way to do this?

harsh python
#

Hello, I'm having an issue with the 2D Beat Em Up package by Osarion, I think it's because I have converted it to using the new input system.

I've posted a thread on the forums if anyone has time to help -- https://forum.unity.com/threads/player-character-walking-off-screen-then-snapping-back-to-border-after-switch-to-new-input-system.1505819/

rain minnow
unreal notch
heady iris
unreal notch
#

oh?

heady iris
unreal notch
#

but saves have never worked cross version on my web builds

swift falcon
heady iris
#

You can inspect the IndexedDB in dev tools. Might be worth seeing if you are somehow getting different hashes after rebuilding the game

heady iris
#

it's just the key that's mangled

rain minnow
heady iris
unreal notch
heady iris
unreal notch
#

different localhost ports

heady iris
#

That is a different URL.

unreal notch
#

I can test on itch.io where I host it... but that will take me a good 30-40 minutes due to build and upload times

heady iris
#

You can always just make up your own path, of course.

unreal notch
heady iris
#

the persistent data path is just idbfs/[md5]

heady iris
#

Javascript uses UTF-16 internally.

#

I wouldn't expect a random number to fall out, though

#

I'd expect an error.

#

I am not familiar with interop between other languages and JS

swift falcon
heady iris
#

But perhaps key is getting coerced into a hashcode or something

unreal notch
#

perhaps the number is a fallback for the error?

heady iris
#

because there's no other meaningful way to interpret it as a string

#

Javascript LOVES coercing types

unreal notch
#

var newKey = UTF8ToString(key); localStorage.setItem(newKey, jsonData);
gonna try this

heady iris
#

yeah, see if that behaves better

unreal notch
#

getting saves to be cross version has been a huge bane for me for months

#

I just havent been able to get it working on webGL

heady iris
unreal notch
#

works fine on desktop, and I've future proofed the save data

heady iris
#

a function that returns either an array of ints or 0 is already weird lol

#

(is it returning a pointer, effectively? i've never touched this stuff)

harsh python
heady iris
#

That would cause the animated transform to actually move.

#

and if it's set up like this

#
  • Player (Has the scripts on it)
    • Model (Has the animator on it)
#

this would cause the player's position to not change, even as the model moves

harsh python
#

it does have root motion enabled

#

let's try disabling

heady iris
#

That's not completely consistent with what you're seeing, but it's the first thing that comes to mind

#

(I wouldn't expect it to snap back when you let go of the move key)

harsh python
#

same issue

#

Yeah... hmmm

heady iris
#

oh, you know what

#

you have a rigidbody

#

but you are also directly manipulating the transform

harsh python
#

I do

heady iris
#

these two things are going to fight each other

harsh python
#

Oh man

heady iris
#

I could believe that the rigidbody would keep clobbering the transform's position until it stops having a velocity

harsh python
#

so i need to stop moving the rigid body in the main move function then?

heady iris
#

I'd retool KeepPlayerInCameraView to return the desired position

#

and then just set the rigidbody's position if necessary

#

maybe use an out parameter so that you can also return if a move is necessary

#

setting the position every frame would mess with momentum

harsh python
#

the keepplayerincameraview function does that I thought?

#

it doesn't maniuplate the rb at all

heady iris
#
bool KeepPlayerInCameraView(out Vector3 newPos) {
  if (bad) {
    newPos = goodPos;
    return true;
  }
  newPos = Vector3.zero;
  return false;
#

something like this

heady iris
#

it doesn't expect to have its transform messed with

#

If you have a rigidbody on an object, you should not manipulate its transform directly

#

You can set the position of the rigidbody directly with rb.position = whatever;

heady iris
#

Is this a 2D kinematic rigidbody?

harsh python
#

Dynamic

heady iris
#

Ah, okay

#

I guess the edge of the screen isn't a collider

#

so it could happily fly off

#

I'm a lot less familiar with how 2D behaves in this kind of situation

#

I know 2D rigidbodies fall asleep pretty aggressively. Perhaps that's what allows it to snap back.

harsh python
#

yeah

#

well, if I change that RB check to transform.Translate(vector), it actually does keep the character in view, but it snaps and doesn't move properly

#

I can try your suggestion too -- i think you nailed it to the wall with the rigidbody thing

#

Thank you!

heady iris
#

no prob (:

#

It's a very common issue that can cause a lot of problems (teleportation, phasing through walls, broken trigger/collider messages)

heady iris
unreal notch
#

ok @heady iris
https://i.imgur.com/M2eJdYN.png

progress... it seems the var newKey = UTF8ToString(key); fixed that issue.... however
something is still wrong, the json being returned by the load function is still coming out empty/null

LoadFromLocalStorage: function (key) {
        var jsonData = localStorage.getItem(key);
        if (jsonData !== null) {
            return allocate(intArrayFromString(jsonData), 'i8', ALLOC_STACK);
        }
        return 0;
    }````
heady iris
#

Same problem.

#

key is not a string

#

I presume it's an int8 array or whatever

unreal notch
#

oh, convert it ins the same way I guess

#

all these string and text format things are so arcane to me

heady iris
#

yeah, I've never touched this stuff

#

i just know JS loves to not give you errors :p

unreal notch
#
LoadFromLocalStorage: function (key) {
        var newKey = UTF8ToString(key);
        var jsonData = localStorage.getItem(newKey);
        if (jsonData !== null) {
            return allocate(intArrayFromString(jsonData), 'i8', ALLOC_STACK);
        }
        return 0;
    }```
lets see if this works.... time to go make another coffee while I wait for another build .-.
heady iris
#

notice how you have to turn jsonData into an i8 array

#

Also, that kind of looks invalid to me

#

ALLOC_STACK implies it's allocating space on the stack

#

But that's going to get freed as soon as you return

unreal notch
#

if this works though, I'll have a huge update coming to my game... auto saves, checkpoints, a revamp to how saving works in general

heady iris
#

It might work because the stack memory will probably not get overwritten

#

but that sounds sketchy

unreal notch
#

well, if I run into problems down the line, I'll know where to look at least

#

thanks for the help, I'll let ya know if it works~

unreal notch
orchid bane
#

Is there a way to get reference to the mesh of quads without serializing anything?

heady iris
#

This contrasts with a heap allocation, which can live for a long time

#

https://docs.google.com/document/d/1A8hen2hLFY5FLkC5gd3JP2Z-IpHfnAX-CpYLK3aOdwA/edit#heading=h.6u7xyqroin5d

I found this linked from a unity forum thread. Notice how it does this:

  // this function returns a string to C#
  ReceiveString: function () {
    var str = "A string passed from JavaScript to C#";
    var bufferSize = lengthBytesUTF8(str) + 1; // calculate the size of null-terminated UTF-8 string
    var buffer = _malloc(bufferSize); // allocate string buffer on the heap
    stringToUTF8(str, buffer, bufferSize); // fill the buffer with the string UTF-8 value
    return buffer; // return the pointer of the allocated string to C#
  },
#

this is a memory leak, of course. it calls _malloc and then immediately forgets about that pointer

#

I am not sure what the "correct" thing to do here is. Perhaps you should store the pointer in a variable and then free it the next time the method is called?

#

You would need to find someone who knows more about Emscripten :p

#

Or you need to be able to free the buffer on the C# side.

unreal notch
hard viper
#

shouldn’t the GC take care of most deallocation?

unreal notch
#

the save file is being read, its accessible, its not null or empty

hard viper
#

idk are you using unsafe mode?

heady iris
#

This is C# <-> JS interop

unreal notch
#

but I'm unable to load into it

hard viper
#

oh shit. then you better not drop the ball on memory allocation lmao

heady iris
#

Although, you could avoid all of this if you just use IndexedDB, I'm pretty sure

#

you wouldn't need to call out to JS code

unreal notch
#

if there is a better solution, I'm all ears

#

I just want my saves to persist between webGL versions, however that happens

hard viper
#

i’m not super familiar with a lot of this, but maybe I could ask where your data is stored

heady iris
unreal notch
heady iris
#

that's why persistentDataPath gives you an /idbfs/... path

unreal notch
heady iris
#

only if you accessed them at the exact same URL every time

#

assuming you used Application.persistentDataPath

unreal notch
#

I think when I upload a new version to itch.io it cretes a new path on their servers for it

#

I have no control over that

hard viper
#

maybe I’m being dumb because I don’t understand a lot of what is going on, but can’t C# just save/write to a file, and then tell JS when it’s done, then JS opens the file? or visa versa?

unreal notch
heady iris
#

JS is being used here to interact with localStorage

#

it's a simple key-value store

#

but C# has no clue about its existence

hard viper
#

i see. good to know

heady iris
#

/idbfs/koboldsshiny/... or whatever

unreal notch
#

in place of persistentDataPath?

heady iris
#

Right.

#

I have not touched IndexedDB from a WebGL game before

#

I might be about to, actually, since I'm making one that I'll want to save settings for

unreal notch
#

I'll give it a try, after I try this thing, cause I feel like im 90% of the way there on this solution

hard viper
#

saving is important. it’s worth it

#

it’s probably the biggest upgrade from the NES era

unreal notch
#

yee
luckily Ive had saves working for ages, and cross version on PC is very simple

#

but webGL gets really complicated because of the restrictions on writing data to the users storage

heady iris
#

i'm reasonably proud of how i did saves in old JS games: i had an array of functions that would convert save version x to save version x+1, and upon loading, it would just index this array with the save's version number over and over and apply the function until the save was up to date

harsh python
#

So @heady iris --- I tried your refactor and it failed. The character doesn't snap back anymore XD

#
    {
        Vector2 playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
        if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width) && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f)
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));

        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width)))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x - screenEdgeHorizontal < 0f))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.y - screenEdgeVertical < 0)
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(playerPosScreen.x, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
        }
        newPos = Vector2.zero;
        return false;
    }```
#

called it here like this KeepPlayerInCameraView(out Vector2 transform);

heady iris
#

You forgot the early return

#

It always hits the end and returns false

#

You can just make it set rb.position immediately

harsh python
#

i tried changing the transform.position to rb.position it didn't work either

#

I am adding the other return statements

#

nah, nothin

heady iris
#

Share both updated scripts on a paste site.

harsh python
#
    {
        Vector2 playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
        if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width) && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f)
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width)))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x - screenEdgeHorizontal < 0f))
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        else if (playerPosScreen.y - screenEdgeVertical < 0)
        {
            newPos = Camera.main.ScreenToWorldPoint(new Vector3(playerPosScreen.x, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
            return true;
        }
        newPos = Vector2.zero;
        return false;
    }
    
    ```
#

that's your suggestion

#
    {

        Vector2 playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);

        if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width) && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
        }
        else if (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width))
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Abs(Screen.width) - screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f && (playerPosScreen.y - screenEdgeVertical < 0))
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.x - screenEdgeHorizontal < 0f)
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, playerPosScreen.y, transform.position.z - Camera.main.transform.position.z));

        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x + screenEdgeHorizontal > Mathf.Abs(Screen.width)))
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width - screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if ((playerPosScreen.y - screenEdgeVertical < 0) && (playerPosScreen.x - screenEdgeHorizontal < 0f))
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(screenEdgeHorizontal, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));

        }
        else if (playerPosScreen.y - screenEdgeVertical < 0)
        {
            rb.position = Camera.main.ScreenToWorldPoint(new Vector3(playerPosScreen.x, screenEdgeVertical, transform.position.z - Camera.main.transform.position.z));
        }
    }```
#

this was attempting to change the rb position instead

heady iris
#

please share these in paste sites. they're very large.

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

you'll want to do a little debugging to see if this code is doing what you expect

heady iris
#

also, you could clean it up a lot by just using some Mathf.Clamp calls to clamp your X and Y position

scarlet kindle
#

Hello, I'm attempting to do a hard reset of the game using the following code:

public void RestartGame() { var allTransforms = FindObjectsOfType<Transform>(); foreach( var tr in allTransforms) { Destroy(tr.gameObject); } // then load the map again SceneManager.LoadScene("Map"); }

But, the data in the singletons isn't being reset at all. Is this expected?

heady iris
#

well, I have no idea how your singletons work

#

are they on DDOL'd game objects?

scarlet kindle
#

yeah, they're the basic ones for MonoBehavior classes that most people use. they use DDOL

#

this type

heady iris
#

I believe that FindObjectsOfType only searches the current scene.

scarlet kindle
#

I did inspect the transforms found, and the Singletons are in there

heady iris
#

hm, okay. do your singletons actually get destroyed? you can have them log something when they die.

rain minnow
scarlet kindle
#

yea good idea let me try that

unreal notch
#

omg it works, finally.... but there is one last issue to solve....

#

I had to forego my error checking to make it work, because I dont know how to check if the file or key exists

scarlet kindle
#

ok so my singleton code is actually a bit different (sorry for lying)

    {
        // start of new code
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        // end of new code

        Instance = this;
        DontDestroyOnLoad(gameObject);
    }```

and the instance is getting destroyed, but it must be the new instance getting destroyed
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

unreal notch
#

in C# for desktop, I do

if (File.Exists(Application.persistentDataPath + "/kobolds.shiny" + i))```
but I tried
```cs
if (File.Exists("koboldsshiny" + i))```
and this did not work, despite the file with that name visible in the localStorage
heady iris
harsh python
heady iris
#

Not sure about the exact execution order here.

heady iris
#

Application.persistentDataPath, in a WebGL build, is /idbfs/[md5 hash]

harsh python
heady iris
#

I presume that your browser interprets asking for a file at /idbfs/ as a request to get something from IndexedDB

unreal notch
heady iris
#

didn't you say you were expecting that second block of code to read data from local storage?

unreal notch
#

I just need a way to check if the file exists on webGL, but I think I have a solution...

#

I see what you meant though

heady iris
#

local storage does not store files, and you aren't going to be touching local storage from C# anyway

unreal notch
#

file.exists isnt the right thinfg to use here

heady iris
#

no, it is, but you need to use a path that starts with /idbfs/

harsh python
#

@heady iris I fixed it

#

turns out all i needed to do was move the KeepPlayerCameraInView() function to fixed update

#

XD

heady iris
scarlet kindle
heady iris
#

(but maybe this was just a more general problem with using IndexedDB)

heady iris
#

that suggests you can...dispose of the object

#

you just want to give them a Reset method or something

#

Perhaps you could create a static event that you can invoke when you want to reload the game

#

and those singletons would subscribe to it

scarlet kindle
#

yea, put them all in one place... cuz I have multiple singleton classes and it could get really annoying doing it in each class separately

#

ok i'll try something like that

heady iris
#

each class would still need to know how to reset itself

#

but you'd just be triggering that from a single place

scarlet kindle
#

right of course, just easier to manage if it's all one in place

#

just make references to each of those classes in the one place... maybe just make that a static class on it's own i'm thinking?

#

a non MB static class

heady iris
#

no, this would be an event

#
public static class Resetter
{
  public static void DoReset() => Reset?.Invoke();
  public static event System.Action Reset;
}
#

anyone can do

#
Resetter.Reset += MyResetMethod;
#

this would add MyResetMethod to the list of functions that get called when Reset?.Invoke() happens

scarlet kindle
#

hmm ok

unreal notch
#

I got it
I can die now

#

the codes not pretty, but it works

#

though... this might have all been for nothing, because I think its still pulling from a local storage directory exclusive to this version of the game.... so I may end up trying that explicit file path

scarlet kindle
# heady iris no, this would be an `event`

Just an FYI, using IDisposeable ->

     _instance = null;
     Destroy(this.gameObject);
 }```

this appears to work exactly as desired, without the extra effort of separate management
heady iris
#

ah, so you meant to destroy the object, not just reset its fields

#

I see what you mean now

#

I thought you wre describing the fields on the singletons being reset

scarlet kindle
#

yes, well it appears to reset the fields as well

heady iris
scarlet kindle
#

i'll need to test more but, for instance the player health gets reset as well

unreal notch
#

what does that exactly?

scarlet kindle
#

which is a field of the MainManager instance

heavy wren
#

has anyone tried testing a UIDocument component? I ran the following code but failed the assertion. I don't understand why the root element is null

    [Test]
    public void CanSerializeComponentElements()
    {
        var puzzle = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/UI/Prefabs/TestDocument.prefab");
        var root = puzzle.GetComponent<UIDocument>().rootVisualElement;
        Assert.IsNotNull(root);
    }
fiery path
#

anyone know why the camera isnt rendering (noob q)

heavy wren
# fiery path

it is rendering, it would be black if nothing rendered

fiery path
#

its strange, added new cameras, used cinemachine

#

everything just equates to grey

#

or sometimes just the skybox

#

checked culling mask, etc

#

must be something im missing

heavy wren
#

it could be a lot of things. It looks like its rendering the ground, if you rotate the camera does it then render the skybox?

rigid island
# fiery path

search t:camera inside the hierarchy. how many cams you have

fiery path
unreal notch
hoary sparrow
#

I have a private object, which in the inspector is a scene and it works well in the editor, but when the game is built it gives me a null reference exception

heady iris
#

I think Scene assets are editor-only?

hoary sparrow
#

ah dang

heady iris
#

but check this out

rigid island
heady iris
#

i stole this from someone on the unity forums

#

i should probably find them...

#

It's pretty simple. It just copies the scene path into a string field when you assign a scene object

hoary sparrow
#

oh, neat

heady iris
#

SceneField implicitly converts to a string, so you can throw it straight into LoadScene or whatever

fiery path
heady iris
#

Scenes are weird. Scenes can only be gotten for scenes that have already been loaded

#

SceneAsset is its own unrelated thing

fiery path
#

new scence fixed this for some reason

hoary sparrow
heady iris
#

Yeah, I dunno what the deal is.

hoary sparrow
fiery path
rigid island
#

You can see the bounds right there

#

hmmm I can see the floor isn't there though so not sure if thats the same cam

fiery path
#

no bro trust me moving and rotating it does nothing

#

also just booted it up in a diff unity version and it works

#

must have something gone wrong during this install

#

using a diff version now and it’s fine

heady iris
#

what versions?

swift falcon
#

Whadup y'all! Hope it's going fine for everyone! Listen, I've got this weird bug where I basically have a function that spawns a terrain, now I want to make the terrain spawn around the player as he moves. It does happen, however, the newly spawned chunk is 100 units further away from the original chunk terrain that is spawned... Here's the code that manages all the work of spawning the endless terrain around the player: https://gdl.space/mevatuxavo.cs. If you don't know how to solve this it's okay but please, if someone could take a bit of their time to help it'd mean the world to me, maybe we figure it out together.. Thanks!

#

hope i made the link properly lol

chrome trail
#

Is a script's OnTriggerExit event supposed to trigger if one of the children attached to the object it's on leaves the trigger? Because for some reason it's doing it for me on one project but not another and I can't think of any reason except possibly version differences

heady iris
#

is there a Rigidbody on your object?

#

physics messages from child colliders will be received by the parent with the Rigidbody

chrome trail
heady iris
#

That is expected behavior, then.

chrome trail
#

It doesn't seem to be doing this in a different project, though, and I can't figure out what's different between the two

heady iris
#

well, does the parent object in your other project have a rigidbody?

chrome trail
#

Yes

heady iris
#

perhaps there are no physics messages at all, then

#

also, I'm not sure what happens if the child object has a component that receives the message

chrome trail
#

The script on the child object processes its own OnTriggerExit events just fine, though

heady iris
#

does the first project not have a component on the child object that receives OnTriggerExit?

chrome trail
#

They both have the exact same components. I made absolute sure

heady iris
#

so, in both projects, you have:

  • a rigidbody on the parent
  • a component on the parent that receives OnTriggerExit
  • a collider on the child
  • a component on the child that receives OnTriggerExit
#

is that the case?

chrome trail
#

Yes

heady iris
#

in the first project, OnTriggerExit is being called on the parent, and in the second project, OnTriggerExit is being called on the child.

#

Show me the inspectors for the parent and child in the two projects.

chrome trail
#

Nevermind. I fixed it. Apparently it was a glitch involving recognition of the root of the collider being exited

rancid frost
#

I am trying to update my mesh. I have added new vertices and triangles to my mesh and verified the triangle count actually increases, but my mesh has no visual changes...why is that?

rancid frost
rancid frost
heady iris
#

please share it properly in a paste site -- !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

I'd like to see the entire scripts

rancid frost
#

with all due respect, all I am doing if modifying the mesh triangles and vertices

#

I dont think that is neccassary

#

that classes fuses meshed together...similar to CombineInstance

rancid frost
heady iris
#

It is very hard to pick through a collection of screenshots. That's why I asked for whole scripts on a paste site.

rancid frost
#

vertex count isnt changing, but tri is

heady iris
#

oh, you mean that the rendering statistics are changing. I was thinking you were checking that the mesh on the mesh filter was changing.

rancid frost
#

that tto is changing

heady iris
#

So your code is not adding any new vertices -- it is just connecting the existing ones together into triangles.

rancid frost
#

the vertices and triangles are stored in an array

#

then we can add new vertices to said array and assign them to mesh

#

it seems the mesh is resetting itself...

#

nvm lol