#archived-code-general
1 messages · Page 205 of 1
This part works. If I comment line 66 out, the messenger spits out a lot of gibberish.
as i know and saw -there no that avoidance system for 3d space
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...
how about something like https://github.com/ricardojmendez/UnitySteer
yes i tried it, it's like 30% of functions rom origin project. and most of only for 2d space
oh i see you're using the string version. if you add a debug right before line 40, do you see that it starts multiple times from here?
You just want to format the timespan as a string in Minutes:Seconds??
Nope. Nothing is being displayed. This is all for code.
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
It starts once each time I press Interact, which is what I want.
Ah, I simply put the Sound.stop(STOP_MODE.IMMEDIATE); line before line 40 and now it works!
kinda weird though, because shouldn't it be the exact same? 🤔
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 ?
honestly not sure because these dont seem to be default unity stuff. are you using some asset?
@lean sail I'm using FMOD as audio middleware. It's pretty powerful 🙂
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
You are spelling things incorrectly and making other such typos
also your IDE is not configured
You must configure it before continuing
!ide
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.
sorry whats configuring it and what difference does it make?
It autocompletes and points out errors for you
Hence:
If your IDE is not autocompleting code
or underlining errors, please configure it:
you will be able to see exactly where the problem is
Ive fixed the errors to code its now just the method to bool error, any idea?
first configure your IDE
Configure your IDE correctly.
then, stop making copying errors from the tutorial code
what copying errors have i made, i cant spot none and i am doing the ide im just new im not being funny
Configuring your code editor correctly would make it highlight the exact error...
based on the error - you forgot a () around there
That definitely helps. Thanks. 😔 I had a feeling I was overcomplicating it somewhere.
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
well, you repeatedly ignored our instructions, so we repeated them.
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.
"i am doing the ide"
just whilst it was being done i just asked if blue knew the fix whilst the config is being sorted
.
@cyan rapids its also a requirement to get code help on this discord
Fen said it once, and then explained why it was important 🤷♂️
And where you said you were doing it was AFTER the one time they said it
lol dont mind it, you should see the attitude I got when asked for a video that wasnt shaking from a phone
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
Have you configured your code editor? We aren't going to get anywhere until you do that.
Yes that is what I am doing
Then, no offense and not trying to be rude, but stop commenting here until you are done. This complaining that the help isn't good enough is just spam at this point.
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
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?
Did you click on "Get the SDK" and then install that?
Did you install the "Unity for Visual Studio Code" extension?
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
Okay, but did you install this extension?
nono sorry i was saying i just dowloaded the dev kit, im assuming download that
Also, after getting the SDK, I always recommend restarting your computer.
But yeah. Get that extension first, it is crucial
The instructions tell you to install the "Unity for Visual Studio Code" extension. You need to install it.
Sorry just double checking, which is it?
thankyou
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
it is now dowloaded but still showing the net core error, is this normal or a worry
You should restart your computer and then check again.
VSCode might be stuck thinking it has no way to get the SDK
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
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
It's alright (:
Totally fine. Miscommunications happen
Now, for you error here
#archived-code-general message
You may have realized this because the ide should point it out now, but:
It looks like you wrote "centre" while it is supposed to be spelled "center" which made the boxcast invalid which is why it is saying it is not returning a bool
Might be another issue for the bool actually, because that is a different line
Yes figured that out whilst waiting thankyiu, the next rrror is a bool error
Cannot convert from method group to bool
Nice. Show that next line of code causing the error
Like Praetor said, might just be missing a ()
It’s saying 35 although there isn’t any code there?
- Save your code
- Check the new error message(s)
- share the code and the full error message(s) here
Hmm. That picture said line 84
And COLUMN 35
so line 35 is safe? sorry i thought it meant 35 and 84 🙂
Yeah, the second number is the "column" (number of "characters" from the left)
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?
If you're asking in this channel and not in #💻┃code-beginner , you should be able to debug this error on your own.
Find the line that throws it. Understand what the error means, find the causing variable. Make the appropriate changes.
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
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.
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
There are 2 types of error: compile errors and runtime errors. The first would be detected by your ide or compiler when your write or compile the code, but runtime errors would only appear at runtime. It means that something in the execution went wrong. It was not possible to predict that issue before actually running the code.
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
So, even if your code "looks fine", there might be problems with it.
To find the line of code, you'll need to learn to read the error message.
Also, it's virtually impossible for us to help you without seeing the error.
Via some editor API, sure.
yeh im trying to find the right api for it
i found this https://docs.unity3d.com/ScriptReference/ObjectFactory.CreateGameObject.html but this still put them in the scene so not sure why this api exists lol
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
Hmmm... maybe this would work with GameObjects.
https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
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
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
Is there a way to create a load screen WITHOUT using LoadSceneAsync? That method just...causes way too many issues
If you know the line, now understand what the error means. Try googling it. Every error has a descriptive manual page in C# manual.
If it's just a mesh, you don't need a gameObject for it.
But yeah, it seems like gameObjects require a scene to be created. So either create a temporary GameObject or a temporary scene for the GameObject and the destroy them after saving to the asset.
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?
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
This doesn't seem to have a way to determine the progress of the scene-loading like with LoadSceneAsync
Not necessarily. Ultimately you debug it through code. But the issue might be somewhere else too. Like something missing in the scene setup that your code expects. You need to read the code and understand what it requires. And if that doesn't help, you either use the debugger to step through the code or log debug messages to the console with helpful information.
because it happens on main thread so everything else waits
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
Yeah, so you'll need to do it in one of the ways that I suggested.
Yeah, should be pretty easy with the scene manager.
I got the Async Load to work properly. It's just that...it causes other issues with UI things for some reason. And I can't find any info on it online. The main problem I'm dealing with is that this UI Image I'm using as an animated transition between scenes just doesn't load in when I use Async
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
Doesn't sound normal. Might want to debug it and share more info on the setup/code.
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?
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
!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.
@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?
Also, what is the actual question?
I don t know if you re saying something
Well, you can reverse the bool that is returned by IsGrounded.
i think i am overthink the math an bit
in the plane challege or at least i am make more diffuclt for myself
if i put a ! before the is grounded is this fixed?
doesnt matter
It would reverse the bool, yes. As for whether it fixes the actual issue is a different story.
It worked 🙂
@cosmic rain your game is interesting i like it
Where do you have the PlayerRunState type defined?
Show it
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
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
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?
Maybe use it's Object ID?
would this be a valid one:
AssetDatabase.AssetPathExists("Assets/Tanks/" + this.GetInstanceID() + ".asset");
i presume instance id is always unique and unchanging?
Yes. It is unique within the project and should be unchanging. It might change on asset reimport though(not sure about that).
oh hmm
Okay. Does the error appear in unity console too or only in the ide?
Like, if the .meta file is deleted I think. As that's what's keeping the id afaik.
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
By keeping the meta file safe I guess.
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.
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()
I don't think you can create an Object via constructor.
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
Hmm... In the docs they use an instance of an SO as a base. And you can create one with ScriptableObject.CreateInstance<Type>()
but isnt the scriptable object already instanced if im generating from a scriptable object's data
Wdym? You create a new instance from type.
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
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
scriptable objects dont have guids do they?
This is an instance already, yeah.
It's unclear what you're trying to do with this ID
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
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
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
Add the meshes to the SO and reference them from it https://docs.unity3d.com/ScriptReference/AssetDatabase.AddObjectToAsset.html
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
Yes, but isn't that your SO?
is an SO considered an asset in the asset database?
wasn't really sure how unity stores them
If it's in the project view then it's an asset
oh
ill try that then
can i save prefabs to it aswell with prefab utility?
or do they have to be seperate
Note: You can not add GameObjects; use PrefabUtility instead.
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 🤔
Your code doesn't really show the full picture. Perhaps you should move to #↕️┃editor-extensions and post what's drawing that field
sure
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
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.
Why blue collider go into red?
just so there isnt a weird tiny gap where the platform isn't
Well one way you could fix it is by making the colliders on the tiles. Not so specific. So like make the tops just a flat square
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
You don't. What you can do is you can go into your Sprite and edit the collision box on it.
Interesting
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
Would probably still prefer some sort of approach that wont get me stuck if colliders arent exactly perfect
Well you have a couple of options. First option is probably box collider, and another option would just be don't fill that little gap in, and another option would be make your sprites go all the way to the end and not stop randomly to fill that gap in.
Are using a sprite sheet?
Im waiting for option3, naturally go over bumps without getting stuck 😄
So you're waiting for your Sprite guy to fix the sprite?
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
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
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
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;
}
this one uses mathf.sin
Hm... So sin in HLSL is not the same as Mathf.Sin then? How would I solve it, do you know?
Eh, guess I can just make my own sin function then
you know unity has a rng right?
That takes a seed or do you mean the Random?
and is the difference decimal?
oh mb
No, completely wrong return value
thats pretty odd. is there a specific return value that you should be getting because it is random lol
and mathf = math(float) so it uses floats
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;
And here is with SimpleRNG(i, seed, -360, 360);
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
it might be a decimal tbh. try debug.logging the values of each one and comparing
Hm... Can we debug.log, or whatever log they have HLSL, I mean, I'll just check, should be possible
might be print
the values u are using are large, so a decimal difference might be major
yea
you could try rounding the numbers
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
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
Genius...
using System;
public class MathFunctions
{
public double Sin(double angleInRadians)
{
return Math.Sin(angleInRadians);
}
}
LOL
you really can just round the number with mathf.round
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;
}
this looks like a series to me
Taylor series
I believe its an approximation
Yup
ah yea, i fell asleep during that lecture and never learned taylor series 😂
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
float value = Mathf.Sin((float)iteration * 12 + seed * 78) * 43758;
value -= Mathf.Floor(value);
I'm already rounding with floor, do you think it would be different?
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
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?
how do i make a configurable joint set its target rotation to face a point?
the objects will be GC'd when they are no longer referenced by other objects (reachable from the "root" of the game)
When will it be non-reachable from the root of the game?
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
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
you need to implement the IDisposable interface and handle it yourself
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)
public SomeClass : IDisposable
{
// Do I call this manually whenever its no longer needed?
public void Dispose()
{
// What goes in here?
}
}
read the docs
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?
you sure you want a bool and not perhaps an enum?
otherwise you'd probably need some custom editor scripting for that
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
Maybe you could do it OnValidate then just store the valid combinations and compare it.
Thatd be a quick way, probably not best
Oh thatd probably be annoying in some cases actually
Yeah I think im just gonna have to sanity check ghe input in some way and put big capital letters in the serializefield tooltips
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
someone is experienced in rts terrain generation and performace? I like to talk about this argument
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.
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.4008Any 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.
This error means that their GPU is out of memory. Either your game or something else is eating up all their memory.
They might be able to see what uses how much memory in the task manager.
@cosmic rain do you happen to have any idea how to fix this?
Not sure a good code fix without many raycasts
Sorry. No clue. Don't do much 2d.
Maybe think of how not to arrive at that situation(with overlapping colliders) instead.
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 🙂
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?
Just the right
Ah, okay. Are you using a box collider for the character?
Capsule collider I thought...maybe I didnt change that though so it might be box
(Turning on pc rn)
Might want to confirm that, as such issues are common with boxes.
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?
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
it's more that your ide doesn't see you changing the variable outside of the constructor so might as well
cool thanks
any real reason to actually make it readonly?
or just to make the ide happy 😄
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)
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
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
https://pastebin.com/cbYUzfCz
Joystick code ^^
Did you put this in the DontDestroyOnLoad scene?
Or do you have a HideOnPause object in both scenes?
hmmm...looks like it might be my SceneUI getting in the way
aka UI Document getting in way of Canvas
DontDestroyOnLoad is a special scene! It's just one that never gets unloaded
that's why it shows up in the hierarchy like that
That sounds plausible to me.
huh, didn't know it was actually a scene itself
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
I do this weird thing so ik my "DontDestroyOnLoad" is created first
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?
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
"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
is this from third party code that you can't modify?
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)
Since you need to completely remove the code that uses WebCamTexture, #if directives will be the way to go.
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?
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
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.
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)
yeah, Visual Studio and VSCode can do that too.
I usually just do it in Unity anyway because it feels safer :p
I will never do it in Unity because I trust Rider with my life
yep
I've used that quite often
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
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?
what is this "player input object"?
The PlayerInput object
is this the class generated by the new input system?
For the new input system
oh, so the component.
Yes
Show its inspector.
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
Please show me the inspector for the player input component.
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
Change the target of Select Grenade to something else. See if the EquipNextThrowable method is still being called.
and here are the properties for the playerinput component
(and see if the new target is now getting called multiple times)
It's calling the new function 3 times lol
does this persist if you change the binding to another key?
also, to partially answer this: you can get some information by logging and looking at the stack trace
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
I looked at the input debugger and the 4 key on my keyboard isn't acting up but let me try changing the binding
well, everything will have a stack trace, but that'll just be series of methods that got called
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
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?
You might have to install it by name. I know that I had to do that for Cinemachine 3.0
Made another input added a binding to it and it's calling functions 3 times as well.
Can you point me to how to install by name?
another input action, you mean?
Same input action asset, just added another action with a different binding
You enter the name and version separately.
Uhh, thanks 😄
So it should be named com.unity.inputsystem with a version of 1.8.0-pre.1
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
That is possible. You should check for that.
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
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
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)
is just doing math in scripts (but a lot of it) not that performance heavy?
computers are pretty good at math
Profile your code if you think there's a performance issue.
okay
Are you sure you're looking at the right object?
"AirBorderBL" and "AirBorderBR" aren't anywhere in that screenshot
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
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
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
Show how you're creating that log entry
actually, just sharing the whole script would be useful
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 :/
well, you are going to have components everywhere
two scripts interacting, and the editors are in them:
Code Quality Warning, this is a massive mess
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
You can use the hierarchy to help organize things a bit.
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
I'll have a look in a lil bit
Thank you very much!
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
!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.
https://gdl.space/azuzitevor.cpp plane is not upwards now
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?)
not totally sure what you are doing...but why not use cinemachine
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 ... 🫠
check _cameraMoveTween.IsActive() before killing it
its best to not kill a tween directly but instead kill the target it runs on or use a handle
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
public UnityEvent one;
public UnityEvent two;
one.AddListener(() => two.Invoke());
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)
or one.AddListener(two.Invoke)
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
do you have any prototypes or art assets?
Hey, is it possible to set padding propreties of a rect mask 2D to a percentage value?
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
Can I somehow restrict the returned types only to those which implement a specific interface?
public interface ITypesWithUuidProvider {
public IEnumerable<Type> GetTypes();
}```
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?
it sounds like you made grid static
I did. But that was to make it shared data between each prefab game object.
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
Elaborate on this if you can?
So like just the class itself?
I've never used C# this much in my life lol. I mostly use go, and C
then familiarize yourself with the basics of the language
Hey is there a tutorial how to use new "Unity Player Accounts" for Unity Authentification ?
anyone able to help me with this?
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?
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"
you can use the nameof operator to get the name of a variable or method you have access to
I do not have access to the variable
or you can use reflection
you can publish a .net core web api project to azure app service to establish the login endpoint that can be called from your clients. web api can accommodate any auth flow you like, JWT, AD, OAuth2.0 etc. But I don't know what you'd want to incur the costs of using AD for a game's purpose. A simple serverless sql server on Azure could do the same, perhaps for less cost.
well then what is the actual purpose of this?
I searched it but it seems it is not possible
like what is your actual goal here
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();
}```
that doesn't answer the question
and it also doesn't help that you aren't even using a real example
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.
so in other words you want to know what event invoked a specific method without that event passing that info along to the method?
The publisher wouldn't really care about who has subscribed to it's event 🤔
Yes nested invoking by info without passing data around
weren't you also already advised not to chain events like that for the specific reason that it makes it harder to debug?
😄 Yes i am thinking to delete this from the project right now
best you can probably achieve is getting the current stack trace. that won't necessarily say what event was invoked though
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
or literally get rid of nested things
You're right tho 
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?
Nothing built in no. You would need a shader that supports rotating textures
Easy enough to make in shader graph
how would I do that? Im trying to make my conveyor belt arrows rotate for my curved conveyor belt
Sounds more like a job for proper uv mapping.
Are you generating the mesh procedurally?
Is there a channel for ar foundation?
Thank you
is it possible to cut a cylinder into the terrain? trying to make a golf hole and failing....
Put a big hole in the terrain and place a mesh there encompassing the golf hole and the surrounding area
this isnt a code question, but u can use the terrain tools to easily raise/lower terrain. You can even use the set height mode to get it the exact height you want. Theres a few tutorials online for how to use terrain tools
help i tried downloading the unity management and scene flow data project ahead of time and i got this error
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.
- this is not a code issue
- have you considered just hitting continue?
No I have not, also I am on unity Learn unit 2
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
Tried a few things, ended up doing this. Worked well and I was able to keep the lerp as I wanted. thanks.
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);
}
}
which os?
macos
I use /bin/bash as the exe and then -c followed by the rest of the command as the arguments
it was my mistake, I specified a non-existent path to the folder where the keistor should be placed....
there is one more small question, I'm trying to get the path to the JDK
string javaHome = Environment.GetEnvironmentVariable("JAVA_HOME");
the command
echo $JAVA_HOME
produces
/Applications/Unity/Hub/Editor/2021.3.0f1/PlaybackEngines/AndroidPlayer/OpenJDK
but for some reason
Environment.GetEnvironmentVariable
produces an empty string
Environment variables are passed to the application when it is launched. It could be that unity just discards unnecessary variables.
how can I get access to /Applications/Unity/Hub/Editor/2021.3.0f1/PlaybackEngines/AndroidPlayer/OpenJDK/bin/keytool in the editor script? It would be desirable for this to also work on Windows.
I think this is dependent on at which level the variable is defined in MacOS
you should be able to get that from Unity Preferences
Isn’t it possible to automatically get it directly from the code somehow?
yes of course, find the preference that holds it then use EditorPrefs
string unityPath = EditorApplication.applicationPath;
string unityContentsDirectory = Path.Combine(unityPath, "Contents");
string jdkPath = Path.Combine(unityContentsDirectory, "PlaybackEngines/AndroidPlayer/OpenJDK");
is this valid for each platforms?
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
i want to use this only in editor
probably not, Windows does not have a Contents folder
Hi. Does anyone know if OnCollisionEnter works if the collider is in its children and the rigidbody is in its parent please?
Yes, it should work.
then idk why it isn't detecting anything
How are you confirming that?
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
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
Sure. Generally better to use your IDE's Debugger and a breakpoint, but that works
still doesn't detect it😅 I might be missing something very basic but idk what
Go through the resource I linked
maybe if I create a new script just to test that
yeah I did
A log is good enough. Or a breakpoint.
If you don't see the log, then there is an issue indeed.
Better check what Vertex mentioned.
Also might want to share more details on your setup.
it takes more than a few minutes to go through, you should be more thorough about it
well basically an object with a rigidbody and a script with that OnCollisionEnter and its colliders are children of that gameobject
oh okay, I'll go through it a bit more, thanks
Does it work if the script is on the same GO as the rb?
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
Ok, then it should work. But just to test, try putting it on the object with the collider.
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
Maybe share a video showing your setup and the issue.
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
It's not quite clear from the screenshot.
Is it the object with the rb?
the object with the rb is this one
and then this is the object that should detect the collision
And like it is clearly colliding with the ground as seen here
I might be missing something very basic but idk what exactly that is
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
I don't see a collider on that object.
it is on its child
Ok, that's not gonna work. The script needs to be on a gameObject with either an rb or a collider.
but like now there's a collider on that same gameobject and still nothing
Mmm... probably not a great idea to move a part of a compound collider. Try giving it a rigidbody.
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
Something like an overlap point or circle.
Or just a trigger collider.
yeah if I give it a rigidbody it seems to work, but I don't really want to have 20 rb on each aircraft😅
Why not?
wouldn't that end up affecting performance?
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
The rule of thumb is that every moving collider needs an rb if you want it to be processed by physics properly.
oh okay
it worked
thank you so much
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;
}
}
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
Unity is caching the last resolution explicitly specified for a build via Scene.SetResolution(). How do you clear that - where is that value stored?
post the code correctly
I want to do more than just auth and simple read/writes to a db. With a serverless sql db, it means I would also have to ship my game with the connection string and password of my db no?
never mind I fix it. I just made a structTemp that save information and then I put that into mi l_matrices like this
but do you understand why you must do that?
yeah I guess this is working due to I save data into my function before to assign a property from my struct instance
The web service would talk to the sql server, not the client directly so clients wouldn't need the connection string. Then you could have either your server or client make the call to the api. I assume you want to authenticate players, but then also maybe persist player data for later retreival? web api is one way you could approach this.
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
@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.
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
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?
there's nothing special about plain old C# classes
You got to call base to* use the previous constructor in c#
{
public DerivedOne() : base()
{
Console.WriteLine("DerivedOne Constructor");
}
}```
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
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
Hm what if i do the DerivedClass serializable?
https://hatebin.com/tgslwiqpeb
heres the code of my save system, and here is the code for my javascript
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?
you don't create a new instance so the ctor won't run. if you just do _derivedClass = new DerivedClass(); the base ctor will execute . . .
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!
i presume that the "string of numbers" is 32 characters long
that's the md5 hash
oh, you're writing to local storage
the keys are just... random and not the string I assigned in my code
Is there a better way to do this?
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/
you need to initialize the field in a method for the ctor to be called. you don't want it to call during field initialization because that will occur within the editor and again when starting the game . . .
the weird thing is, even if I rename the key to the proper string, it still doesnt work, the json in my LoadGame() function always comes back null
it computes the hash of part of the URL, by the way, so different versions of the game would have the same hash
oh?
Application.persistentDataPath points to /idbfs/<md5 hash of data path> where the data path is the URL stripped of everything including and after the last '/' before any '?' components.
but saves have never worked cross version on my web builds
I am confused at this point. When i dont use new() to declare the variable while the parameterless constructor is implemented inside of DerivedClass, the constructor actually fires somehow. Will it work for build tho? I will test now
public DerivedClass derivedClass;
You can inspect the IndexedDB in dev tools. Might be worth seeing if you are somehow getting different hashes after rebuilding the game
I was going to suggest that the extern method was getting called wrongly, but the actual data looks fine
it's just the key that's mangled
this is what i did: https://hatebin.com/hnqrtvoybf. definitely test in build, but it should work fine . . .
Although, you call UTF8ToString on the data, but not the key.
yes, I am
I have two different versions open atm and they have different hashes
same url, though? i would expect different simultaneous versions to be at different places
different localhost ports
That is a different URL.
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
You can always just make up your own path, of course.
do you think this will solve the issue?
the persistent data path is just idbfs/[md5]
I am wondering if it's trying to interpret a UTF-8 string as a UTF-16 string
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
Okey without new(), the constructor wont get called in build. But in editor, it does. Thank you for testing with me i got it now 😄
But perhaps key is getting coerced into a hashcode or something
perhaps the number is a fallback for the error?
because there's no other meaningful way to interpret it as a string
Javascript LOVES coercing types
var newKey = UTF8ToString(key); localStorage.setItem(newKey, jsonData);
gonna try this
yeah, see if that behaves better
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
me when there's zero static typing and minimal runtime type errors: 🫠
works fine on desktop, and I've future proofed the save data
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)
Any chance I could get some eyes on this? It seems like a simple problem but it's been driving me nuts for hours --- I can't make sense of it.
Does your animator happen to have root motion enabled?
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
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)
oh, you know what
you have a rigidbody
but you are also directly manipulating the transform
I do
these two things are going to fight each other
Oh man
I could believe that the rigidbody would keep clobbering the transform's position until it stops having a velocity
so i need to stop moving the rigid body in the main move function then?
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
the keepplayerincameraview function does that I thought?
it doesn't maniuplate the rb at all
bool KeepPlayerInCameraView(out Vector3 newPos) {
if (bad) {
newPos = goodPos;
return true;
}
newPos = Vector3.zero;
return false;
something like this
right, but that means that the rigidbody is getting surprised
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;
thus:
if (KeepPlayerInCameraView(out var correctPos))
rb.position = correctPos;
Is this a 2D kinematic rigidbody?
Dynamic
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.
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!
no prob (:
It's a very common issue that can cause a lot of problems (teleportation, phasing through walls, broken trigger/collider messages)
also, i realized that this method was on the same class, so you could just replace all of the transform.position = with rb.position =
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;
}````
oh, convert it ins the same way I guess
all these string and text format things are so arcane to me
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 .-.
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
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
It might work because the stack memory will probably not get overwritten
but that sounds sketchy
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~
if I understand the logic correctly, its allocating space in the stack for the decoded json, not the save file itself, its data thats going to be reread each time a save is loaded, so it should be fine?
dunno if I'm understanding that correctly though
Is there a way to get reference to the mesh of quads without serializing anything?
Allocating memory on the stack just pushes the stack pointer down by the number of bytes you want and returns a pointer to the start of that new region of memory.
This contrasts with a heap allocation, which can live for a long time
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.
ok....
more progress, but still not functional....
shouldn’t the GC take care of most deallocation?
the save file is being read, its accessible, its not null or empty
idk are you using unsafe mode?
This is C# <-> JS interop
but I'm unable to load into it
oh shit. then you better not drop the ball on memory allocation lmao
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
if there is a better solution, I'm all ears
I just want my saves to persist between webGL versions, however that happens
i’m not super familiar with a lot of this, but maybe I could ask where your data is stored
my understanding is that you can interact with IndexedDB roughly like a filesystem
wait lmao, I never updated my loading code
easy fix perhaps
that's why persistentDataPath gives you an /idbfs/... path
but if that were the case, wouldn't my saves have been working cross version in the past?
only if you accessed them at the exact same URL every time
assuming you used Application.persistentDataPath
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
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?
the problem is, web browsers are very limited in their ability to write to a users storage, for security reasons
JS is being used here to interact with localStorage
it's a simple key-value store
but C# has no clue about its existence
i see. good to know
I'd see what happens if you use an explicit path for IndexedDB
/idbfs/koboldsshiny/... or whatever
in place of persistentDataPath?
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
I'll give it a try, after I try this thing, cause I feel like im 90% of the way there on this solution
saving is important. it’s worth it
it’s probably the biggest upgrade from the NES era
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
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
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);
You forgot the early return
It always hits the end and returns false
You can just make it set rb.position immediately
i tried changing the transform.position to rb.position it didn't work either
I am adding the other return statements
nah, nothin
Share both updated scripts on a paste site.
{
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
📃 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.
you'll want to do a little debugging to see if this code is doing what you expect
oh sorry
i.e. that it's setting the position when you expect it to
also, you could clean it up a lot by just using some Mathf.Clamp calls to clamp your X and Y position
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?
yeah, they're the basic ones for MonoBehavior classes that most people use. they use DDOL
this type
I believe that FindObjectsOfType only searches the current scene.
I did inspect the transforms found, and the Singletons are in there
hm, okay. do your singletons actually get destroyed? you can have them log something when they die.
can you confirm that they're deleted?
yea good idea let me try that
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
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
!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.
3 backticks, not one . . .
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
I wonder if this is leaving you with the dead objects in the Instance fields.
Those things are already clamped in another function
Not sure about the exact execution order here.
this has nothing to do with localStorage
Application.persistentDataPath, in a WebGL build, is /idbfs/[md5 hash]
@fen https://paste.myst.rs/zut3l157
https://paste.myst.rs/53oavrwu
here are the two versions
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
I presume that your browser interprets asking for a file at /idbfs/ as a request to get something from IndexedDB
I know, I'm saying thats the if statement I use when NOT using webGL/local storage
didn't you say you were expecting that second block of code to read data from local storage?
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
local storage does not store files, and you aren't going to be touching local storage from C# anyway
file.exists isnt the right thinfg to use here
no, it is, but you need to use a path that starts with /idbfs/
@heady iris I fixed it
turns out all i needed to do was move the KeepPlayerCameraInView() function to fixed update
XD
I'm not sure if that will work properly, though. I see a post talking about how writing data to a custom path doesn't persist after leaving the page.
Very old post, mind you
I think it is, would implementing an IDisposable -> Dispose() method call, where I reset the Instance fields be a safe way of dealing with this?
(but maybe this was just a more general problem with using IndexedDB)
i wouldn't implement IDisposable
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
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
each class would still need to know how to reset itself
but you'd just be triggering that from a single place
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
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
hmm ok
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
Just an FYI, using IDisposeable ->
_instance = null;
Destroy(this.gameObject);
}```
this appears to work exactly as desired, without the extra effort of separate management
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
yes, well it appears to reset the fields as well
localStorage is separate per-origin
i'll need to test more but, for instance the player health gets reset as well
what does that exactly?
which is a field of the MainManager instance
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);
}
it is rendering, it would be black if nothing rendered
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
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?
search t:camera inside the hierarchy. how many cams you have
yeah it doesnt render the ground (cube) but you are right
the gray is just the bottom of the skybox
just the one
nevermind, save persists between version on itch! successful test~
\o/
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
I think Scene assets are editor-only?
ah dang
but check this out
check for virtual machine cameras maybe.
also this is not a code issue
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
oh, neat
SceneField implicitly converts to a string, so you can throw it straight into LoadScene or whatever
i am aware just thought it would be a quick fix
ive been using unity for years ive never had this
ill just make a new project
thanks for the help anyway<33
Scenes are weird. Scenes can only be gotten for scenes that have already been loaded
SceneAsset is its own unrelated thing
new scence fixed this for some reason
that is a bit confusing, weird there is no nice way of loading scenes by default, other than strings
Yeah, I dunno what the deal is.
just tested it and it all works exactly as I hoped, thank you very much!
In fact nevermind, complete new secne and nothing?
Is it potentially my Unity version (2022.1.15f1) or a URP issue?
Your camera is looking into the horizon dude
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
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
what versions?
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
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
is there a Rigidbody on your object?
physics messages from child colliders will be received by the parent with the Rigidbody
There is on the parent object, but not the child object
That is expected behavior, then.
.
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
well, does the parent object in your other project have a rigidbody?
Yes
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
The script on the child object processes its own OnTriggerExit events just fine, though
does the first project not have a component on the child object that receives OnTriggerExit?
They both have the exact same components. I made absolute sure
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?
Yes
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.
Nevermind. I fixed it. Apparently it was a glitch involving recognition of the root of the collider being exited
can someone help?
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?
check the chunkprefab transform in editor and make sure the position isnt 100 units away
Show your code.
please share it properly in a paste site -- !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.
I'd like to see the entire scripts
with all due respect, all I am doing if modifying the mesh triangles and vertices
I dont think that is neccassary
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
that classes fuses meshed together...similar to CombineInstance
it works, tnx
was that the issue?
Where are you checking that the triangle count has changed?
It is very hard to pick through a collection of screenshots. That's why I asked for whole scripts on a paste site.
vertex count isnt changing, but tri is
oh, you mean that the rendering statistics are changing. I was thinking you were checking that the mesh on the mesh filter was changing.
So your code is not adding any new vertices -- it is just connecting the existing ones together into triangles.