#archived-code-general
1 messages ยท Page 59 of 1
should I just refactor the code, or is there something obvious that I'm missing.
Yes. You'd get the correct amount after the elapsed time rather than spontaneously adding torque.
That's probably a better way to do it than what I've been doing, thank you!
someone else had the same problem and they never got it fixed 
This didn't work. If the Inspector is open in debug mode and I press the UI button it throws houndreds of the errors...
What kind of events are you subscribing to? Are you sure they fire every frame?
Definitely
For example: I'm trying to implement an interaction interface
When I press the key for the door, it opens and closes like 20 times
Well, we'll need to see the code. Otherwise it's just assumptions.
Trying to press the key for only 1 frame is essentially impossible
although I don't think I need help anymore
I'll just refactor it
cause although it won't be pretty
I can just use the method i've used for other first person controllers I've made
and just use that input handling
Take it off debug mode
mmhh mmhh, yep. Problem is a I am trying to figure out what is going wrong with the button.
What do you need the inspector in debug mode for
The button's background image only works once, and then once I click it the background stays on the default background. Also then once I click anywhere else the button background works again. I am not messing with the the button on script side either. I was trying to see if one of the private variable states was only switching back once I click again.
Like the hover over highlight stops and no press button, I can still press the button though.
Hey all! Trying to write code that adds all images (just jpgs and pngs) from the player's pc to a list that can then be drawn from in a random selection function. I know it needs to use stuff like Environment.GetFolderPath(Environment.SpecialFolder.Desktop) but don't know how to piece it all together
Scanning the user's entire file system is going to be an extremely slow process
Oh no I meant more so just places where images commonly are
I'm only scanning desktop, downloads, documents, and the images folder
Uhm personally as a player i would find this kinda invasive
Even that can potentially take... well forever basically, depending on how many files they have, how slow their drives are etc.
You'll want to do the scanning in a background thread for it to be reasonable
Also this
That's kinda the point lmao
It's a file manipulation game
Use an in game file system
:doubt
Inb4 "file manipulation game" just means manipulating the files so you can charge ransom for them
Anyway you'd basically use
https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.enumeratefiles?view=net-7.0#system-io-directoryinfo-enumeratefiles(system-string-system-io-searchoption)
I'm just going to stay very far away from your game though
Thank you!!
Can't blame ya for not trusting me but I promise it's just a cute lil game about generating flowers out of player images
It always starts that way...
Also uh
It took you a bit to come up with that?
And reading the players every image isnt great anyways
Imagine you read the sussy folder on their desktop
It's going to be super slow and yes also this ^
Does anyone know what the non-"prefab edition" of navmesh is, and how I could use it?
I don't recall using any navmesh prefabs
I have no idea, but are you using com.unity.ai.navigation?
I'm using a fork.
Maybe it's coming from that library.
My understanding was that this dialogue is from Unity core
Why are you not using the ai package?
The one you mentioned?
Yes
Because it doesn't support 2D colliders
Or, at least, it didn't when I first set up navigation.
But I'm still using NavMesh, which is (confusingly) not part of that package.
My best guess is that "prefab edition" means non-DOTS, and that there's a DOTS package that will allow you to use the same NavMesh object without GameObjects.
My guess would be it means you're in prefab mode or something
Ah, yes yes. I am editing a prefab hahaha
"prefab edition" wtf is that wording
Must be a typo on "prefab editor"
Oh, "edition" as in "the act of editing"?
๐คท
Yeah looking at the source it's about prefab mode https://github.com/needle-mirror/com.unity.ai.navigation/blob/5355cfb57e645b2eaf59fb90ce87d7220468f4bc/Editor/NavigationOverlay.cs#L195
No idea why they've called it edition, but I do imagine it's just a mistake
Can anybody help troubleshoot this for me? It seems to just set my texture to be black
for (int i = 0; i < texture.width; i++)
{
for (int j = 0; j < texture.height; j++)
{
float xPos = i / texture.width;
float yPos = j / texture.height;
float alpha = Random.Range(0f, 1f);
Color color = new Color(xPos, yPos, 0f, alpha);
texture.SetPixel(i, j, color);
}
}```
have you called Apply?
Also, you are doing integer division
you should be casting one side of the division (the denominator is most common) to a float
Ah I see thank you!!
is it possible to change the 'CurrentRunSaveData' class reference for a string that's being defined elsewhere in the code?
essentially I want to use the string to define a class reference
That's metaprogramming. It's complicated and not recommended.
hm ok
I decided to use the string to define the folder I'm looking in, essentially I'll be creating three folders with the same file name but different data, whereas I was going to originally have 3 different files with three different names in the same folder
which is probably better practice anyway
Imo, this constructor for this class is pretty unwieldly. Is there a better way to write this, or is this just the way it's supposed to be?
public class Tool : Item
{
float rockStrength;
float sedimentStrength;
float organicsStrength;
float entityStrength;
public Tool(float rockStrength, float sedimentStrength, float organicsStrength, float entityStrength, int id, int amount, int maxAmount) : base(id, amount, maxAmount)
{
this.rockStrength = rockStrength;
this.sedimentStrength = sedimentStrength;
this.organicsStrength = organicsStrength;
this.entityStrength = entityStrength;
}
}```
Rather than a bunch of separate fields would you be better off with something like a Dictionary<StrengthType, float>?
Or make it a scriptableObject and set the fields in the inspector
quick question, How to run export unity's project on Mac M1 ? I've tried but Xcode return files .dylib and i didn't know how to run it on Mac.
Hey, so I'm working on a pet project which start to get relatively significant. Everything works well except one thing, I have a METRIC TON of spaghetti code right now. ๐ for instance on my character, I have a character controller to handle its movement / rotation, an animator controller to handle animation changes, an AI script to handle a FSM for its AI. Pretty organized you'd say, but still, everything is interlaced, each script has references to the others, and they all call functions from one another. It gets more messy now that I integrated some controller and AI logic from animation events. And this is just for my character, my weapon system is also messy and others as well.
Do you guys have any good resources about how to organise the code, and how to architect the project well for it to be scalable without having too much pasta?
you could make a custom data object for the parameters.
constructors with long list of parameters are a smell, overreliance of primitive data types (like float etc) is a smell too.
smell doesnt always mean bad, but is often worth thinking about redesign
if you already go the length to input a data object, i wouldnt use dictionary, to easy to mess up the initilaization. do a proper object with fields, that way the compiler will slap you if you mess it up
Could you elaborate a bit on custom data object?
basically a class that encapsulates the data you need.
class ToolProperties {
float rockStrength;
...
}
its essentially just a statically typed dictionary
struct ToolStrength
{
public float RockStrength { get; set;}
public float SedimentStrength { get; set; }
public float OrganicsStrength { get; set; }
public float EntityStrength { get; set; }
}
public class Tool : Item
{
private ToolStrength _toolStrength;
public Tool(ToolStrength strength)
{
_toolStrength = strength;
}
//...
}
right, struct is even better ๐
Record struct if you wanna get even fancier :^)
Though I think Unity doesn't support them (yet)
what are you harvesting with your tool that it has an "organics strength" ๐
guys i created a camera script that moves the camera to the average position of the player and the mouse
to make the top down feel more active
but that made the player movement laggy
here is the function where i update the camera position
void UpdateCamera(){
Vector2 myPos = (transform.position + c.ScreenToWorldPoint(Input.mousePosition)) / 2;
//new Vector3(myPos.x, myPos.y, -10)
c.transform.position = Vector3.Lerp(c.transform.position, new Vector3(myPos.x, myPos.y, -10), Time.deltaTime * 10);
}
void Move(){
rb.velocity = dir.normalized * speed;
}
What function are you calling the move function in
And also have you turned interpolating on your rigidbody?
nvm i fixed it
how?
there was too much going on one script
i created a seperate camera script it it worked
idk if thats the solution
but it worked
Is there a way in Visual Studio Code to have code completion for Classes and such which are from unimported namespaces? For instance here, I'd like Intellisense to propose me Transform and if I accept, it automatically import UnityEngine
#854851968446365696 contains info for properly setting up your IDE. AFAIR though, the VSC plugin is no longer supported. you'd be better off moving to VS or Rider
i am trying to set a GO on 0,0,0 position, this should place it on top of the parent. but it gets placed on 0,0,0 in the scene. How can i make my GO get on 0,0,0 in its parents 'enviroment'
Does the position explicitly show 0,0,0 or is it some weird value that ends up at 0,0,0 in global space?
Because AFAIK setting it to 0 would put it at the center relative to the parent
random number that is 0,0,0 in global
i want this ye
Then you should modify transform.localPosition probably
ill try
(I honestly didn't even know there was a whole different method for that)
General question: in a case like this one, if the duration variable is global and it never actually changed value, is there any point in feeding it to a function? (this case that coroutine)
As I said, its global, value set in start, and never changes value.
If you'll want to reuse your coroutine with a different value at some point, yeah. And you never know what you might need in the future, so it's good to make things modular from the start.
I generally prefer to pass anything to a local variable, should your behaviour change in the future. It's generally also just easier to read.
But no, not much difference if you're confident you won't change it.
I can see how that may be efficient, but with this one is a somewhat short Coroutine (13 lines) and it will be on maximum 2 instances simultaneously, still, for the sake of a good habit I think I will make a separate script with my function and place it on my objects.
Thanks u both
I also think this might solve a problem which i encounter sometimes, when i sometimes restart my project my scripts reset their variables to null values and I dont get why, so I started giving the values in the start function to be sure
Instead of having a separate script for the function which is called from the main script of my object I think I can also put everything in one script and have my variables set using a switch statement on the name of the object
im curious what pocket jamming is
hey,
is it possible to make a public list on the editor without the (+ and -) buttons ?
For what purpose? So it cannot be modified? There is no built in way to do that.
You can download something like Odin inspector or Naughty Attributes which give you the option of a [ReadOnly] attribute.
Property drawers apply to collection elements, not the collection itself so that will not work
Really huh. Well then ๐๐จ
I found a bug yesterday
I think list get corrupted after deleting an item of it on the editor (inspector)
I have a custom class the holds info of the scene objects , its NAME , COunt in the scene and GUID
once i delete one of the items from the list on the inspector and try to load it again the list get corrupted
i looped through it , the name is correct , the count is correct but the GUID of all item became " 0000000000000000000000000" what is going on ?
I think I ran into a bug this time...
unity 2021.3.5f1
@vagrant blade @quartz folio
any ideas?
You can use ReorderableList. I believe it has an overload for whether to show add/remove button.
Usually you'd report it to the forums and bug report services, not Discord moderators. https://support.unity.com/hc/en-us/articles/206336985-How-do-I-submit-a-bug-report-
Hello,
I load color image from path and I want convert this image into grayscale.
To SetPixel Texture.isReadable must be true, but when I load image I am not able change isReadable.
Do you know some solution to convert color image into grayscale?
Thank you in advance for your help.
im not confident about that ๐
I've emailed them and opened a ticket 10 days ago but I didnt get any response from them since then.
I've even replied to the same ticket " is anybody there ??? ... hellooooooo ?? does anyone care about those tickets ??? "
I got nothing for days since then ๐
I dont think they care about those tickets at all ๐
but thanks for ur suggestion , i might report it anyway , I was just hoping that the problem is much simpler than that or i messed up or something.
how do u use the ReorderableList ? do i need to add/include something before using it ?
is it like ReorderableList<T> ?
Bugs would only be relative to native implementations. Assuming you aren't modifying the collection and inspector serialization process, the elements should not change.
Its in the UnityEditorInternal namespace. Last I checked there weren't official docs, but this guide helped me start to use it: https://blog.terresquall.com/2020/03/creating-reorderable-lists-in-the-unity-inspector/
Else it's a custom script serialization gone wrong.
You should show your code if you're doing something unusual like serializing stuff from the inspector in a specific way
i have two buttons in the inspector , 1 collect the items with debug read the items that just added to the list to make sure that it was collected successfully , which it does.
and another just reads the list.
when I press the read list button before modifying the list .. everything is great and normal , i can read every item in the loop correctly.
but if I modified the list .... some references became NULL and values like GUID became "000000000000000000"
all this is happening in Editor mode ,not the play mode , so I dont think anything has changed because nothing is running
upload some code so we can see if something is wrong
Modifying the list will make the one your read button refers to not the same as what's modified - likely the issue.
Make certain to reacquire the list from the component on change/validation; basically, if there's a cache, it'll not represent the new list (assuming you've got a cache or internal reference to the collection rather than acquiring it every read)
I'll simplify it in a little bit and upload it because Im using a custom class
PayDay 2, there is a ECM jammer that disables all electronics on the map, and its little brother version the PocketJammer that does the same thing but for a shorter time
I think i found a way around it though
in the same function as im adding items to the list I've also added items to _tempList which is not being modifed
then when I modify the original list ... original list gets corrupted but _templist is not.
that is my current way around
What does UnityEngine.SceneManagement.SceneManager.GetActiveScene(); return if there is more than 1 scene loaded?
The active scene is the one that is bolded in the hierarchy
What about during runtime?
I have mainmenu scene that is persistent and I load in scenes that contains different world areas (only 1 at a time) so while playing there's always 2 scenes loaded
any benefits of using var instead of the actual object type here? I'm confused by rider's suggestion
readability... its a hill some people will die on lol. use var if you want or explicit types... the compiler will let you know when it needs something specific
i prefer explicit types but most people i talk to like var
the primary argument i get is when you have long names and stuff
you can already see what type it is on one side of the operation, so it's not adding anything but verbosity
ok since we have the cast in GetComponent but it's not always the case
its super easy to toggle entire solutions (even millions of lines of code) to switch between explicit and var
that's generics, not casting
When it's not the case Rider doesn't show the hint
Aha it's so obvious and I wouldn't have expected it to be able to be set by us. Nice. I can defs use that and get it workng. Thanks
you're right my bad
oh well rider is actually amazing
@quartz folio that is exactly what is going on but ofc I had to havely simplify it
public void SaveGUID()
{
org.prefabs.Clear();
org._tempList.Clear();
foreach(GameObject GO in org.prefabs)
{
CustomClass C = default;
c.guid = GetGUID(GO);
org.prefabs.add(c);
org._tempList.add(C);
int index = org.prefabs.IndexOf(C);
CustomClass _SavedGUID = org.prefabs[index];
Debug.Log($"GUID:{C.guid}");
}
}
public void LoadGUID()
{
foreach (CustomClass C in org.prefabs)
{
Debug.Log($"GUID:{C.guid}");
}
}
is .guid just a string?
those are editors functions and
GetGUID( GameObject go ) {AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(go)));}
.guid is GUID not a string
the whole issue is when I remove one of the items on the list via inspector , then try to read it again , all GUID gets corrupted and I have some other refrences in the class turns into NULL
the way around is to have 2 lists
I don't see where you're informing the editor you've dirtied these objects, do you call Undo or use SerializedObjects anywhere?
nope
all i do is click on this
@quartz folio ugh, why doesSceneManager.LoadSceneAsync(...); take a scene of type string, whereas SceneManager.SetActiveScene(); takes a scene of type Scene
seriously
because the Scene doesn't exist before it's loaded, and having one generally means you can use it to perform operations that expect it to be loaded
Mmm but you can get a type Scene by build index which isn't a loaded scene
It almost certainly is a loaded scene
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.GetSceneByBuildIndex.html
This method will return a valid Scene if a Scene has been added to the build settings at the given build index AND the Scene is loaded.
Ah okay
Fair enough. I also just found SceneManager.GetSceneByName(string scene); which does the trick without fussing around
well what does the (-) do ? does it "dirtied." ? ... I think it does otherwise the changes shouldnt have been made at all.
but even if it does , why does it courropt some of the refrences and not all of them , i have a string variable in there that stays untouched even after everything is either null or curropted , I know that by looping through the whole list and print its properties ... the name is fine
but guid and other refs are nulled out
im gonna use the trick i figured out for now and hopfully someone would fix it in newer versions ?
Changes can be made, they are just transient, and if you pull from the serialized data you only get what was saved there previously
AAAHH I should have been setting the active scene to the world scene this whole time. Now when I load into the game scene it uses the correct lighting settings from the game scene rather than continuing to use the lighting settings from the main menu
So much better now
so you probably just have that string and whatever else that appears to survive actually serialized because you edited them via the inspector
valid point!
anything edited in code without dirtying in some manner will not survive any change that requires serialization, which includes easy stuff like restarting the editor
My UI which has only a few buttons and images takes up 500ms to SetActive(true)! How do I handle it?
Dive deeper into those calls to get closer to the root cause of why TMP is such a hog
Though, it's hard to tell, it doesn't look like TMP is to blame here?
Nothing much there?
Ah there you go, it's compiling code
if you're building with IL2CPP that lag would disappear
because it wouldn't do any 'just in time' compiling
So I have to endure it in editor?
Pretty sure you don't have a choice sadly

how do i get the start lifetime of a particlesystem, .startLifeTime is deprecated so idk if i should use it
hey, got a questions about addressable reference, couldn't find anything in the internet
so i want to acces specific component from the asset reference but don't really know how
ParticleSystem.Particle.startLifetime isn't ๐ค
oh
But that seems to be the particles life time, not the particlesystem one.
time Playback position in seconds.
i changed it to
smokeVFXDuration = explosionVFX.transform.Find("SmokeParticle").gameObject.GetComponent<ParticleSystem.Particle>().startLifetime;
but i got this error
ArgumentException: GetComponent requires that the requested component 'Particle' derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponent[T] () (at <e8a406da998549af9a2680936c7da25a>:0)
Grenade_Script.Start () (at Assets/Scripts/Grenade_Script.cs:58)
.GetComponent<ParticleSystem>().time; I would think
ok ill try that
Normally if something gets deprecated, Unity would link towards a replacement, are you sure you don't get any suggestions?
uh-
What did you do? 
idk
ok nvm idk what happened
tried this it logged 0
At the start it would be 0 of course
supposed to log 0.75
It's just started probably
no like im trying to get how long the particle lasts
so i just use .startlifetime?
From the particle yeah
Hello everyone,
Is there a way to deserialize a json with a key with a space inside like "Life Max" for instance ?
I'm trying to use JsonUtility.FromJson with my class
[FormerlySerializedAs("Life Max")]
public int Life_Max;
But it doesn't work ๐ฆ
ParticleSystem.main.startLifeTime, seems like it's that one.
smokeVFXDuration = explosionVFX.transform.Find("SmokeParticle").gameObject.GetComponent<ParticleSystem>().main.startLifetime;
So that should work, probably ๐
ok it works now ty
Hi! Can i by somehow launch LoadSceneAsync while timescale is 0?
can someone who knows DOTween, help please? thank you very much:
#๐โanimation message
can someone help me so i am trying to limit head movement for up and down and soon left and right and i been trying to use clamps and its not working ```cs
PlayerHead.transform.eulerAngles += new Vector3(Mathf.Clamp(updown, -2.8f, 2.8f), 0, 0);
var angles = PlayerHead.transform.eulerAngles;
angles.x = Mathf.Clamp(angles.x + updown, -2.8f, 2.8f);
Player.transform.eulerAngles = angles;
ty i will try that
so im trying it now and not the head dont even move and i tryed changing the value it just snaps back to the middle i also got thos 2 errors
Neither of those are related afaict
thats what i thought but was not sure
No idea what the former is, and the latter is from a different script (I assume)
on the last line u sent me should that be player or player head ? ```cs
PlayerHead.transform.eulerAngles = PlayerHeadAngles;
Should be PlayerHead, yes.
There was no Player in your original code
ya so im not sure why this is not working i found out that the head keeps facing up and i have no control over it
Look at the rotation values in the inspector
It may be appropriate to use transform.localEulerAngles instead actually
If you hover it will tell you that you're not initailizing two of your fields
Which is required for struct
objectPosition and objectRotation need to be set in the constructor
oh
In general, you should hover over the red line to see the error
ya you're right
but im trying to implement level streaming in my level
Is coding the only way to do it?
in the inspector i only see the y value moving shouldn't the x value be the one moving ?
Lists are reorderable by default in Unity inspector
And have been for the last few major versions
Maybe starting in 2019? Perhaps earlier
that is great news , im in 2021.3.5f1 but how do i use it right to remove the add and remove buttons from the inspector ?
Oh... I don't know about that sorry. I use odin for that stuff.
It's good but not free
But if you have money I would recommend it, you'll save its value in time almost immediately.
thanks but I wanna build my own function, its not for me.
I just want the following list to be rendered without buttons
public List<CustomClass> someList = default;
Does anyone why im getting this error
following a tutorial on YouTube and I did the same thing but still getting the error
If you hover over it, what does it say?
Should be [System.Serializable] I believe
Show potential fixes
nvm i found the right document , thanks all
So click that, and your done 
so they changed it
?
Depends on what you mean by that, in the general sense yeah, I use it for my game
Unity terrain by default has streaming of chunks
like the whole world it self is not loaded
Yeah I load it by 100x100 meters
there is only be a bit loaded depending on where you are
so do I really need to do all this coding to achieve this
Depends on what you are making to be honest, I don't know how big your game will be. If you want an endless world you would probably want to do all this coding.
There is an asset on Asset Store I used years ago. It seemed to work ok from what I remember: https://assetstore.unity.com/packages/tools/utilities/world-streamer-36486
But your game would need to be huge.
Also making a huge world isn't difficult, making a huge world interesting is.
Then it's rather pointless imho.
lol ya but its gonna be high quality at the end
You could just use occlusion culling to occlude the rooms your not seeing.
how can i make lonely mountains style bike movement using rigidbody?
and our clients apparantly dont have the best computers
have you looked into addressables?
well its funny cause the last video is the playlist is about that
He does a bunch of coding before that tho
well addressables isn't dependent on world streaming. Just another tool in your memory managment toolbox.
please can someone help me out i dont need any code i just wanna know what i should do i want to make lonely mountains downhill style bike movement but i dont know how
beginner to unity editor here: how can i store/embed data about a scene in the editor, for use in runtime i am making a dynamic loader for maps and want to have a text file or something that has data about it
i do modding though so im not a beginner to coding
i essentially just want a txt file that i can read off of
actually reading the channel description this doesnt go here
my bad
I'm running into problems trying to make a network list of a class that includes nullable types. What is the best way to do this?
Don't crosspost in multiple channels. You're being helped in #๐ปโcode-beginner
Hey ! Can I ask for PlayerControl help here ( Wall jumps)?
Don't ask to ask, just ask.
If people can help you, they will.
bro
.
i posted this before
I need some assistance on my wall jump, I don't understand why it does, teleport me to somewhere else,
heres the code
private Vector2 wallJumpingPower = new Vector2(2f, 2f);
private void WallJump()
{
//Si on glisse sur le mur
if (isWallSliding)
{
isWallJumping = false;
//Mรฉthode pour changer l'angle du Player (sprite.flipX)
wallJumpingDirection = -transform.localScale.x;
wallJumpingCounter = wallJumpingTime;
CancelInvoke(nameof(StopWallJumping));
}
else
{
//si C'est false:Diminuer le compteur
wallJumpingCounter -= Time.deltaTime;
}
//Si le compteur est actif
if (Input.GetButtonDown("Jump") && wallJumpingCounter > 0f)
{
isWallJumping = true;
rb.velocity = new Vector2(wallJumpingDirection * wallJumpingPower.x, wallJumpingPower.y);
//Empรชcher de sauter plusieurs fois
wallJumpingCounter = 0f;
//Changer la direction du Player (Flip)
if (transform.localScale.x != wallJumpingDirection)
{
isFacingRight = !isFacingRight;
//Vector3 localScale = transform.localScale;
//localScale.x *= -1f;
//transform.localScale = localScale;
transform.Rotate(0f, 180f, 0f);
}
//Appelรฉ une fonction avec un dรฉlai
Invoke(nameof(StopWallJumping), wallJumpingDuration);
}
}
private void StopWallJumping()
{
isWallJumping = false;
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
//Vector3 localScale = transform.localScale;
//localScale.x *= -1f;
//transform.localScale = localScale;
transform.Rotate(0f, 180f, 0f);
}
}
}
Try isolating the moment where it teleports. You can place Debug.Log statements with the current step and log your current position to see when it changes.
Heya, I have been stuck on a weird way of movement for ship simulation game. Little bit of background information: this VR ship simulation has been a ongoing project that has been passed down between students. The last student that worked on it wanted to give the ship movement but the simulation is also multiplayer (the student before that implemented Mirror to achieve this). The student got the ship moving by moving the world instead of the ship (to not have to move players and the ship and avoiding major syncing problems). Only problem is that the world only moves correct when you do not โrotate the shipโ. I got rotation working by rotation the world around the ship, but I have no idea how I can combine rotation with movement, to make the ship move in arches instead of spinning in a straight line. Does anyone have an idea how I can achieve this?
I tried, it seems like its in the force, however i dont understand why it does teleport instead of a jump
Too much force, perhaps?
You can always try changing it, or any value for that matter
Considering the velocity change is like the only relevant thing here
Does anyone know how to make a custom image in a custom editor window?
I am trying to make a level editor but I don't know what methods I could use to implement it
sounds like something for #โ๏ธโeditor-extensions
Having a bit of a weird one with WebGL build.
Trying to save data from within Unity to get picked up by a browser script.
In main.jslib:
SetData: function(data){
console.log(data);
window.unityOMData = data;
}
in console:
=> 56469088
data is supposed to be a JSON object
tried lowering the force, it does not teleport anymore, but it doesnt go upwards
just straight to the side
That's very weird... Not sure what could be the issue to be honest
Maybe try playing with the values some more
Is there a way to check which UI element I'm hovering with the new Input system?
patch selectable.onpointerenter and get the name from the selectable __instance
I'm not sure I understand how to do that
harmony
Also I made my own selectable class so idk if that's a possibility
what does it inherit from
Monobehaviour
๐
Is there no way I can tell what the raycast is hitting?
show code
if you have a RaycastHit it should be in there
use the out param
I don't use it directly, I'm using OnPointer interfaces
What should I show? I don't understand how that's helpful
and why you need a custom selectable
lmfao
show the entire class
Cos I wanted to make my own buttons and navigation menus
Having a bit of a weird one with WebGL
Hey,
is it possible to make Unity Reorderable List collapsable like any regular List<T> or Array in the inspector ?
Am I just supposed to throw thousands of line of code at you for my buttons, slider, dropdown menu, etc...?
It's working
well
I want to know what I'm hovering
I didn't implement the interfaces in the selectable class, but in each inheriting class
Well, if it ends up not being possible, you might be able to make a custom property drawer?
I mean if your answer is to debug.log(this) in OnPointerEnter, I could have guessed
this is the built in ReorderableList , i might do it but its probably just their but I just dont know how to use it yet
because List<T> has it
Dunno
But I mean if it ends up not actually being available, you can make it yourself.
And if you can't make it for that type because it already exists, you can also inherit a custom type from it
exactly , that is a good planB , PlanA is to actually use the built in method , which is what im trying to figure out right now , whether or not the built in method has it?
What's your issue currently? The convo is a bit long
You can look at your EventSystem's inspector while playing to see what your cursor's ray is hitting
I'm running into issues when trying to make a network list of a class that includes nullable types. I get the error: The type 'Character' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'NetworkList<T>', which obviously means that I can't include nullable types in my list. So, what is the best workaround for this?
I don't think you can with the new Input system.
I've had the issue several time, but I guess searching the hierarchy for selectables works.
Anyway, solved the initial problem
Thanks for the help
I have this issue where my character controller kinda gets stuck on edges
I say kinda because if you move away you fall off
not sure how to fix this issue
You're using gravity right?
yes
How did you implement it?
In the air state player.velocity.y += player.gravity * Time.deltaTime; FinalVelocity += moveVec += player.velocity * Time.deltaTime; player.trueMomentum = FinalVelocity;
worth noting is that when this bug happens im in the ground state
You're doing jump as well?
in the ground state
{
player.velocity.y = Mathf.Sqrt(player.jumpheight * -2f * player.gravity);
}```
You're not checking if the player is grounded?
because the player is already in the ground state
Kk, what triggers the air state?
What triggers that? How do you change isGrounded? You're doing a spherecast I'm assuming?
Im using the character controller
the character controller has a groundcheck implemented
so i figured a spherecast would be redundant
Right, because that issue typically happens with spherecast, to be more specific when the radius of the sphere casted is less than the radius of the character controller then isGrounded can be set to false while the edges of the characters are still touching the ground
Just to double check, isGrounded is false when your character gets stuck right?
is says that isGrounded is true when this happens
maybe step offset has something to do with it?
Step offset is important when you climb up not down
please can someone help me, i want to make lonely mountains style bike movement but cant figure out how????
if you look here you can see the edge is higher than the bottom of the collider
no, the issue was getting slightly stuck, i think raising the step offset fixed it
You can use a rigidbody for physics. Did you look at any tutorials yet?
i have but i havent found any
You can use a world space joint (like ConfigurableJoint) to stabilize and possibly rotate the bike
Bike/vehicle physics isnt an easy subject though
yeah
That's what you would most likely use to move a RB
i wont add suspension though
yeah
but then the turning must feel nice but a little bit slippery just like in lonely mountains downhill
ill propably add a empty gameobject for the orientation
Yeah, I don't see how step offset would affect climbing down steps, it's meant for automatically climbing up
the issue was i was stuck and couldnt go up
I thought your issue was getting stuck climbing down
That's what it looked it in the picture lol
Yeah, increasing step offset would let you climb up bigger steps
right now im adding drag to mkae it a little bit slippery
Slippery? Sounds like low friction, not drag
All what this does is register inputs, what you asked for would require mountains of lines of code lol, so just break is down and make one thing after the other until the entire behavior is complete. So you need something like:
- Torque
- Angular momentum (to avoid sharp turns)
- Gravity
- Suspension
....
It was just a small todo list I came up with on the spot, you need to study the desired movement behavior and break it down and implement it step by step
actually increasing the step offset created a new issue, when I jump against something that is slightly above jumpheight, the character jitters slightly
So the way step offset work, when your character is walking on a plane and suddenly there's a step, the character stops, let's say the step height is 0.3m, so if you set the step offset to 0.4m you're basically telling the character to climb up any step that's less than or equal to 0.4m. Now if you are facing a 0.6m step you won't climb it since the height is bigger than the step offset, let's say your jump height is 0.5m, so when you jump and collide with the terrain, character controller would calculate the step and determine that it is only 0.1m (the total step height is 0.6m, but you jumped 0.5m), and since that's smaller than the step offset it'll climb it, that's where the stuttering comes from I think
yo i have a slight issue, my character goes on slopes and stuff, nvm 2 issues ig XD, 1st the movement is slowed down from going on slopes, 2nd when i stay in place the character starts to slide off, same goes for terrains and stuff, tho ig thats to be expected, lemme know if i should share the movement code
You mean when you're climbing slopes the speed is slower than normal? And the you're static you still move a bit?
yep sliding off of it(the slope)
You're probably using rigidbody then
yea i am
Yep, that's why
the drag is set to 6 and the physics material have 0 friction
Freeze the movement and rotation in all axis if you don't need them
i dont see a reason to be it, i also have slope detection and stuff for slopes soo i was thinkin that might be it
on rigidbody?
position cant be frozen since i cant move the player then
as for rotations everything is
You're using .AddForce()?
There's no need, I understand the issue, lemme see the documentation real quick
Is there a way i can make a login system using only UGS and not using third party providers?
alrighty thanks
Yes, Unity authentication
The same github repo I sent you recently also contains a ReorderableList attribute. Just FYI.
Unity Authentication has either anonymous sign up or third party signup. Is there a way that i can use unity authentication to make users register and save it in UGS?
Without using those third party providers
i made it like this
Yes, UGS is created to take care of everything, Cloud Save let you save your players data in Unity's servers, the sign up implementation might seem like you need to meddle with third parties but you don't, it's necessary to follow the steps in Unity authentication to activate Google play or Apple or Facebook, those implementations are all considered first party and necessary
But is it possible not to use anything like google or facebook or apple? I want to have some sort of direct login to my game and dont want users to sign into google, facebook, apple, etc
Can you set the drag to a higher value?
I believe it's possible to set it to infinity I think, I'm not sure, if not just try a higher value
It's necessary, how else are you going to use Google Play or Apple or Facebook without not letting them confirm players identity?
You must have an account in those platforms to sign in, and they'll try to confirm your identity for the first time
welp lemme try
My game will be webgl
sorry wrong discord
My game is in webgl and want a way to save players progress in cloudsave. I was thinking of username and password setup and dont want to get any more of their data beyond that. I dont need to use those services nor need to confirm anyones identity nor get a certain players data. All i want is a way to save players progress and acess that progress in a new device
so i did, main issue is then my jumping, since the drag is high it requires alot more forces, 2nd issue is if am moving and jumping then if i do that the jump will be even higher
Im looking at it but i cant see option for collapsable, does it has a different name/title maybe ?
https://stephenhodgson.github.io/UnityCsReference/api/UnityEditorInternal.ReorderableList.html
if I want a spherecast without a range (in place) can I just set the distance to 0 ?
or should the direction be the zero vector
For this behavior you need your own servers, the idea behind using Facebook, Google, Apple is that the player data is stored on their servers, and you need to let them confirm your players identity
Yeah, simply reduce the drag before jumping, and increase it again when you're standing still
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
Physics2D.IgnoreCollision(GetComponent<BoxCollider2D>(), collision.collider, true);
}
}
This code works expected however it still detects the initial collision; in which all subsequent collisons are ignored, i want the initial collision to be ignored
how can i go about this
this I think?
https://docs.unity3d.com/Manual/LayerBasedCollision.html
If you want a spherecast without a range then you probably don't need it, its purpose is to report objects with specific components while within the radius of the sphere, sounds like you want to use the wrong solution for whatever problem you have
yes that is exactly what i want
i just do not want to move the spherecast along the direction
i might even try to use a sphere to move around
A spherecast without a range is a unidimensional point
no that is a spherecast without a radius
That would not work as the enemy object still needs to detect collision from the player
So they need to be on the same layer
Yes, that's what I meant, if the radius is zero then it's a point
yes but that is not what i asked thank you
then explain what you're looking for exactly , I'm confused by your post
Mb
What I'm saying is, if you set the radius to zero thel it'll probably won't detect anything anymore, since it's not a sphere anymore, it can't report which object is inside it since it became a point because the radius is Zero
the movement aint as smooth as before when i do the drag even if i fix the jumping :/
chat gpt suggested to counter the slope force, tho no clue
Can you describe the movement behavior before and now?
the movement is alot more snappier
the stopping especially
Try increasing the drag a bit while moving, rigidbody is quite trickier than character controller
Essentially the enemy has a script in which once the player enters its range, a circle collider, the enemy will move towards the location. However I want the player to be able to walk through the enemy and not collide with its poly collider and affect its movement. They both have colliders on them to prevent them going through walls.
The enemy has 2 colliders one for it's "vision" (circle collider) and one for it's hotbox(poly collider)
Hitbox
so make hitbox a trigger only use that for damage , put the other two colliders on a no-collision in layer based collision ignore ?
the hitbox layer doesn't need to be on the ignore layer for movement colliders
since it's separate
so like smoothly interpolate it?
Is using scriptable objects a good way to make a stats system
For events in C# is it better to use static, or to create a singleton for my event? I'm leaning towards static rn since the singleton will just end up being static anyways
Yeah I think that would work
What? You don't need to do either - and probably shouldn't.
sorry, im noob at C# so what should I do?
You can use SO's to store unchangeable values of the items and stuffs like that, it's quite robust for that use case
also instead of just saying don't do X, or Y, please provide valid criticism as to why not, otherwise its not really a productive comment
I would usually, but I didn't understand what it was you were saying. C# events are just fancy delegates
public event EventHandler MyEvent
so i'm not sure what you meant by "is it better to use static". That's like saying "For integers in C# is it better to use static?"
is this what you wanted?
I belive he wants his events accessible from everywhere in an easier manner than "public" that's why he said static or singleton
Yes, so I already have my EventHandler, but I need to register observers for my event from another script
and I dont really want to pass a reference of my EventManager to that said script
I could use dependency injection in the form of FindComponent or GetParentComponent but that also seems meh since its a runtime operation (granted it will only fire once in start)
Yeah so if the event is something global and important then yes you can use static, just don't use it very often, singletons are designed for a different need (mainly persisting data across scenes) so in this case they would work as well but not the best tool for the job
It's best to avoid static as much as you can as well
I agree, C# is not my main language, but I come from java and static is definitely seen as "evil"
That's correct, that's why they're best used in Start() and not Update()
Alright, well thanks for the insight, I'll probably just use static for now as its not a super large project. Should I find problems with static ill probably switch to dependency injection
Any method of searching for components trashes performance in Update(), because it's cycling hundreds of components every frame, that's why it's best to use them in Start() and cache the returned value in a variable so you can use that variable instead of looking for the component all over again
does anyone know how to edge match with a cellular automata generation
void DrawTiles() {
if (map != null) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Vector3Int pos = new Vector3Int(-width / 2 + x, -height / 2 + y, 0);
tileMap.SetTile(pos, (map[x, y] == 0) ? grassPrefab : waterPrefab);
}
}
}
}
this is the method i use to draw the tiles
after the cellular auto procedural gen finishes
but how can i make the tiles edges also be pro gened like the rotation of the tiles i have a bunch of sprites have to
form the edges in a straight and corner form
https://media.discordapp.net/attachments/711401260930301973/1085609168863502366/image.png?width=1440&height=320
So the best thing you can do is cache it, to avoid static
Let's say the component you're looking for is MyClass
MyClass _myClass;
void Start()
{
_myClass = ....GetComponent<MyClass>();
}
void SomeMethod()
{
_myClass.yourEvent += ... //the nomarl event sub;
}
Anyone know why OnRectTransformDimensionsChange is getting called every frame instead of only when the RectTransform dimensions are altered?
Probably because the dimensions of some RectTransform parenting the object you're tracking are changing
You need "using UnityEditor;"
Im calling this on an object with no parent object, it is a canvas (ScreenSpace - Camera)... does this canvas technically resize every frame to the size of the camera even if the camera/screen size does not change?
If you're using a tile map, look into Tile Rules that can do it for you automatically. Just have to configure the rules from the Inspector
Probably so, otherwise your callback wouldn't be updated every frame
Will have to dig in Unity Docs to make sure
do you know of a simpler way to detect when the size of the screen actually changes/window is resized?
ooooohhh
i never knew that even existed bruhh
Simply store the value of screen width and height and compare them to the current values, if it's changed then call your method and make sure to update the stored values to compare them again the next frame
so theres no other event i can check? will have to manually achieve this through Update()?
Not to my knowledge
https://answers.unity.com/questions/969731/how-do-i-check-if-the-screengamewindow-has-changed.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
thats a shame, but it will have to work. thank you
Yeah, it's a simple script, just copy/paste it
yeah very easy to implement, just like to avoid using Update() when possible
Most Unity's events are updated on Update lol, there's no downside really, try disabling and enabling that script you won't see any difference, not even in microseconds
hey dude i was using the rule tile and idk why this looks like this, am i doing something wrong
I have absolutely no idea, I'm a developer
Ask in #๐ผ๏ธโ2d-tools
๐
Why is this not generating the triangle?
{
WaitForSeconds wait = new WaitForSeconds(0.01f);
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Proceduarl Mesh";
vertices = new Vector3[(xSize + 1) * (ySize + 1)];
for (int i = 0, y = 0; y <= ySize; y++)
{
for (int x = 0; x <= xSize; x++, i++)
{
vertices[i] = new Vector3(x, y);
yield return wait;
}
}
mesh.vertices = vertices;
int[] triangles = new int[3];
triangles[0] = 0;
triangles[1] = xSize + 1;
triangles[2] = 1;
mesh.triangles = triangles;
}
Both sides
Ok I don't think it's anything wrong with the script maybe something with urp
Dont happen to be missing a MeshRenderer component maybe, or its position is off somewhere funky?
private void Start()
{
int xSize = 5;
int ySize = 5;
Mesh mesh;
gameObject.AddComponent<MeshRenderer>();
gameObject.AddComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Proceduarl Mesh";
Vector3[] vertices = new Vector3[(xSize + 1) * (ySize + 1)];
Vector3[] normals = new Vector3[(xSize + 1) * (ySize + 1)];
for (int i = 0, y = 0; y <= ySize; y++)
{
for (int x = 0; x <= xSize; x++, i++)
{
vertices[i] = new Vector3(x, y);
normals[i] = Vector3.back;
}
}
int[] triangles = new int[3];
triangles[0] = 0;
triangles[1] = xSize + 1;
triangles[2] = 1;
mesh.vertices = vertices;
//mesh.normals = normals;
mesh.triangles = triangles;
}
this works fine for me, i get a pink triangle, even without specifying normals. (specify your normals)
Not sure where can i ask this but i'm using PlayOneShot(), the issue is that the sounds as time passes get slowed down! The AudioSource's pitch is still at 1, I don't understand what kind of issue is this, first time happening after using Unity for so long
Center of the RT in world space?
That would be Vector3.Lerp(p1, p2, 0.5f), where p1 and p2 are diagonally opposite corners
For some reason it still doesn't work
I don't understand
how are you calling Generate? Are you using StartCoroutine? Otherwise it'll just stop at the first yield
I am using StartCorotuine
Hey hey ๐ Is there a way how to run debug (attach process) via vscode in 2023 ? I know there is legacy extension, but I am just curious if I can use vscode with unity?
the VSCode debugger is not maintained and can't be expected to work really
Why not use VS Community instead? It has many debugging tools built-in already
I just like vscode ๐ Thats why ๐ But for sure I can use VS Comm.
hi.
[ReadOnly] tag is always highlighted in red , something is missing, what could it be ?
"Highlighted in red" means there's an error message
read your error messages
they tell you important things
using Unity.Collections; << I figured it out , I just needed to add that ๐
yeah it said , you are missing derivative or namespace bla bla bla ๐
but you are right thanks โค๏ธ
"Are you missing a using directive?" < important.
using Unity.Collections; < this is the "using directive" it's referring to
Yea i get what u mean , i have deleted again to see the message and the possible solutions , yeah it was one of the possible answeres , its important to pay attention to the error message ๐
thanks โค๏ธ
I need to have an object which is vertically anchored to one object and horizontally anchored to another... is there an easy way to do this in editor or with a simple component? or is it best to just do this in Update() via script?
what is the use case, what are you trying to do
align a ui element with two other elements which are part of different layout groups
it needs to be in the same horizontal position as some elements above it, but needs to vertically align with another element on the other side of the screen
is there channel where i can ask for help with installing unity?
Needed tips to get this (sorry for the amazing art !!), just want to know ur thought on how u would do this.
The user throws a "Lego like" block, which on landing on the ground (lego blocks as ground) will be attached to the nearests (if only have one just one). Just the "attach" part is where i would appreciate some advice. Detecting which ones collided without adding for each "teeth" a collider, or a script making the level not optimised. Sorry if should put this on another channel!
looks good
ok so depending on the rest of the context, you might predetermine the angle right when the user 'throws' it, then make it smoothly go towards the exact point you want it to be to look 'attached'
Anybody know how to set the input system backend to both via code? I checked PlayerSettings class, the activeInputHandler property is not coming from there, its some custom editor
var playerSettings = Resources.FindObjectsOfTypeAll<PlayerSettings>().FirstOrDefault();
if (playerSettings == null)
return;
var playerSettingsObject = new SerializedObject(playerSettings);
playerSettingsObject.FindProperty("activeInputHandler").intValue = 2;
playerSettingsObject.ApplyModifiedProperties();
Actually have an "angry bird" throw like, so thought to use particles and move it/teleport to the closers
Repositioning it correctly, to not have it between them
so it's a physics based game? then yeah that might be wiser
hey,
how to reorder a list ? like switching between index 3 item and index 4 item ?
var temp = list[2];
list[2] = list[3];
list[3] = temp;
Thank you โค๏ธ , I thought there is a built in meathod in unity list<T> that i dont know about
someone does their leetcode ๐
Might be still, but do you need it?
i feel u want me to say "No" but i dont trust myself that much lol
I would rather go with something done by someone else ๐
I don't think there is, Linq would've been your bet, but I don't think it mutates the original collection ever
yeah this one is a not that complicated and you are the one who solved it not me so i trust it ๐
And works with any amount of variables, as long as there's the same amount left & right
im not sure how would that work on a list item ? , maybe a vector2 but a list ? i dk
Sure, that would be (l[0], l[1]) = (l[1], l[0])
Using tuple swap makes me irrationally happy
and the computer would be ok with that ? ๐ , it hates me when I add a bracket on my own lol
i'll give it a try ๐
hey is there a way to get the positions/illuminances of lights that a particle spawns?
Hey guys im trying to make a grid system for my game from scrtach and i got this code here and i was wondering how can i spread the points out?
@narrow summit @simple egret
hey, unfortunately, both methods doesnt seem to be working.
I just want to point out that Im testing them via inspector button and not on run time
basically im running a function asking list to switch between item no. 4 and 3 then loop through all entries and tell me each order with its order.
nothing has changed based on what i read on the debug
Post code
Increase the value of SpaceBetween. In the loops, for the vector calculation you should be multiplying, not adding
oh thanks
You should test in playmode. Edit mode has its quirks which I don't think you're accounting for.
Anyway, if you need edit mode, post code!
hey thanks man but is there anyway to move the grid as well like for me i need it to start at the floor but currently its above floor?
Sure you can declare another Vector2, modify it from the Inspector, and add that to the other vector in the for loops
That will "offset" the grid by a specific amount
Or attach the script to an object that's aligned with the floor
And yeah, that works
new Vector2(...) + Offset; also works, and looks cleaner IMO
thank you
Oh 1 more thing but i dont need your help i just need to know if im on the right track.So this grid will be used for my building system right?So i have abutton to spawn a building sowhen i click that building a building will instiate and it will follow the mouse.So in order for this building to snap to the grid i round the posison to the nearest point on the grid correct + the mousepos right?
Yep, you would take the world position of the object, subtract it from the grid's origin so the position is "relative to the grid", then divide that position by the SpaceBetween, and round down.
That way, it works even if you change the size of the grid
so do you mean like the grids first point by relative to the grid?
Yeah, as you add an offset, you now need to subtract that offset so the position calculation is adjusted to the origin
ok
wdym round down?
likewhere in the equation?
bc right now i have this
Say your grid cell size is 10, with an offset of 20 on both axes.
You now place an object in world space at (42, 42), and want to adjust it for the grid.
Subtract the offset: (42 - 20, 42 - 20) = (22, 22)
These coordinates are now adjusted, relative to your grid.
Divide by cell size: (22, 22) / 10 = (2.2, 2.2)
Round the positions down: (2, 2)
Your object is to be placed inside cell (2, 2) of the grid.
Now, multiply that back by the cell size: (2, 2) * 10 = (20, 20)
And add the offset: (20 + 20, 20 + 20) = (40, 40)
The position snaps to (40, 40) which is the closest grid point to (42, 42)
(going offline for the night now)
ok
wait is my equation rgiht?
Like bc my grid dosent have a cell size
SpaceBetween is the cell size
oh okay
Should probably rename that variable
so we should put this equaion in var right?
yeah
ok
then we set the position to that
Your equation is almost right, just got to put the offset subtraction in parentheses, as the division is done first here
Order of operations issue
Then, once it's adjusted, you multiply it again by the cell size, and add the offset
And done, it's now snapping to the grid cells
Then apply the second part of my sentence, here ^
Nope, still not
But can you expalin the math
Parenthesize the subtraction
Oh
(a - b) / c
Still need to multiply and add the offset back
in the same equation?
Yeah, after that. You don't want to put the result of the rounding into the position yet, because what the rounded vector returns are grid indices, like indices of an array in code
Say this returns (5, 1), that means "the 6th grid cell on X, the 2nd grid cell on Y"
It's not world positions anymore
so we minues 1?
No, you keep it as is
This is correct right?
As if you put an object at (9, 8), it will get rounded down to (0, 0) which is the bottom-right cell
so wait
how come?
Because with a cell size of say 10, it'll do
9 / 10 = 0.9
8 / 10 = 0.8
Rounded down
0, 0
First cell
Indices start from 0 just like everything in C#
Sorry to ask a question in the middle of actively trying to help someone, but am I right in concluding that the reason my character isn't responding properly to AddForce right now (trying to implement a knockback mechanic that pushes them backwards when colliding with enemies) is because the movement code is using MovePosition on the rigidbody and it's basically trying to move the same thing in two different ways at once?
OOOOOOH Okayy sowhat should w edo?
Follow the instructions you've been half-ignoring for the past 10 minutes
WAit im confused
OOOH
I see
i dident see that mb
i belive this might work now
Still missing the second half
Well you're doing that in the middle of the first step
After dividing, but before rounding down
So I really have to go to sleep now so just have some pseudo code
adjustedPosition = objectPosition - offset
indices = RoundDown(adjustedPosition / cellSize)
// the 2nd half, convert indices back to world positions
objectPosition = (indices * cellSize) + offset
Try to work with that alright? The first part of your code, where the division is, is not correct anymore
is the entire equationwrong?
On this one, yeah. You don't want to use RoundToInt either because sometimes it rounds up. You absolutely need it to always round down
You can cast to int, for that.
(int)3.1 // 3
(int)4.9 // 4
It gets rid of the decimals, essentially rounding down
There's also FloorToInt
alright
gimme as ec to type up
wait a sec
wegpt
a
oki got it
but its kinda TOO act=rate
like ineed it to inbetween the points
but think i all i need to di divded
Whats the best way of organizing npc AI scripts? Id like the NPCs to change what theyre doing. For example daily tasks, go home to sleep at night, and hide/run away when attacked
Would it be best to write script for each state and then have the npcs use the scripts specific to circumstance?
Have you heard of Finite State Machines, or Behavior Trees?
No, Im brand new to this. But thanks for the mentions Ill start reading about it and following tutorials now
I keep reading mentions of large projects being terrible for beginner game devs, but would it be bad to have a large project and work on it in small chunks?
Sending this problem here because #๐ปโcode-beginner is occupied right now, and this seems like a pretty complex problem too that I can't solve.
I'm making a first person character (classic way to start Unity 3D), and all is well. I learned the basics of the code very well and have a somewhat solid understanding of what I'm doing (except Quaternions, I can't stand Quaternions). The only issue I'm still facing is that when I run into an object at an angle, my camera will do a jitter of sorts as I keep walking. Once I leave the object, it is fine though.
This link is both the player movement script, and player camera script: https://hatebin.com/mkbqgierun
I narrowed down the issue quite a bit. The player capsule itself is not jittering, but rather the camera position holder that possesses the player camera script (the parent of which is the player capsule.
I have found that the issue is related to the RigidBody's Angular Velocity, which increases when this jitter also increases.
So my question is what in the world do I do?
Not sure if calling rb.MoveRotation from Update (in your CameraScript) is causing the weirdness but I would do that in FixedUpdate
I would also try zeroing the rigidbody's angularVelocity continuously
Actually, try freezing your rigidbody's Y rotation completely in the constraint settings. You should still be able to rotate via MoveRotation, but collisions shouldn't affect your angularVelocity
Third solution did it, thanks osmal (:
For future reference, I tried moving MoveRotation to FixedUpdate, and it made the camera rotation much more jittery whenever looking around, probably because it isn't linked to each frame.
Zeroing AngularVelocity is what I did in the beginning actually, and it helped end jittering once I stopped touching the object. I decided to delete it since it didn't work before I asked for help, yet its effects remained after I had removed the line of code, weird. Anyways I added it back but it didn't change much, it only helps end jittering when the collision ends.
Now, the jittering is over, but my character is very prone to sticking to the wall when walking at it, even if its not a direct angle at all. Is there a way to end wall stick?
Nice to hear that it worked๐
probably because it isn't linked to each frame.
Yeah that's probably it, there's a disconnect between the camera and rb rotation.
my character is very prone to sticking to the wall when walking at it
Try adding a physics material with low friction to your capsule collider. I like to keep it at 0 or near 0 so I have more control over the movement
Anybody here played desktop love story? Looking to imitate their falling image windows
Worked great, I gave it very low static friction so wall stick doesn't occur when standing still, but kept the dynamic friction so I don't slide across floors after walking or jumping. You've been a great help with this problem, can't thank you enough.
Essentially I want it to start a process which opens a txt, then makes the notepad window "fall"
hey,
is it possible to get the GUID of a file ? (*prefab or a scene *) ?
or perhaps AssetDatabase.TryGetGUIDAndLocalFileIdentifier if you have the object instance id?
https://docs.unity3d.com/ScriptReference/AssetDatabase.TryGetGUIDAndLocalFileIdentifier.html
thanks , but it returns GUID as a string , is there is a way to convert it to GUID?
Guid has a constructor that takes a string
could u give me an example or the document to it ?
new Guid(myString); ๐คทโโ๏ธ
var t = AssetDatabase.AssetPathToGUID("Assets/cool.png"); var guid = new GUID(t); Debug.Log(t); Debug.Log(guid.ToString());
edited
actually
you need the Unity struct
capital GUID
otherwise you get -
@potent sleet Thanks !! โค๏ธ
Can someone help me? I am getting this error
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <1f66344f2f89470293d8b67d71308c07>:0)
HeterophoriaTest.isMinimum (System.Collections.Generic.List`1[T] peData, System.Single currentPrism, UnityEngine.Vector3 eyePos) (at Assets/HeterophoriaTest.cs:447)
HeterophoriaTest.alternateCoverTest () (at Assets/HeterophoriaTest.cs:420)
HeterophoriaTest+<RunDistantTest>d__55.MoveNext () (at Assets/HeterophoriaTest.cs:232)```
This is my method it is referencing
```private bool isMinimum(List<PrismEyeData> peData, float currentPrism, Vector3 eyePos) // Somehow needs to be called multiple times to double check it is the correct value?
{
PrismEyeData currentPEData = new PrismEyeData(currentPrism, eyePos);
peData.Add(currentPEData);
peData.Sort(); // IDK I think it should sort the added values so it can bracket easier?
int currentindex = peData.IndexOf(currentPEData);
if (peData[currentindex + 1 ] != null && peData[currentindex - 1] != null)
{
if (peData[currentindex].eyePosition.x < peData[currentindex + 1].eyePosition.x && peData[currentindex].eyePosition.x < peData[currentindex - 1].eyePosition.x)
{ Debug.Log("Is bracketet and is minimum"); return true; }
else { Debug.Log("Is bracketed, but is not minimum"); return false; }
}
else { Debug.Log("Is not bracketed // Error is logic."); return false; }
}```
Here is how it is called `isMinimum(prismEyeDataList, prism, currentEyePosition)`
I only created the list like this `private List<PrismEyeData> prismEyeDataList = new List<PrismEyeData>();`
Here is the PrismEyeData Class incase it is needed.
{
public float prismValue { get; set; }
public Vector3 eyePosition { get; set; }
public PrismEyeData(float newPrismValue, Vector3 newEyePosition)
{
prismValue = newPrismValue;
eyePosition = newEyePosition;
}
public int CompareTo(PrismEyeData other)
{
if (other == null) { return 1; }
if (prismValue < other.prismValue) { return -1; }
else if (prismValue > other.prismValue) { return 1; }
else { return 0; }
}
}```
I am thinking maybe the issue is that the PrismEyeData Class doesnt have any MonoBehaviour, but I had an error for some reason having it on the class.
I just now noticed these warnings for the PrismEyeData Class The referenced script (PrismEyeDataArray) on this Behaviour is missing!
The referenced script on this Behaviour (Game Object 'OVRCameraRig') is missing!
The problem is you accessing the list with an out of bounds index like the error suggests. For example this line:cs if (peData[currentindex + 1 ] != null && peData[currentindex - 1] != null)
So either currentIndex + 1 is greater than or equal to the size of the list, or currentIndex - 1 is below zero
Hmm how can I fix that error...? I think there is also an issue with the List itself, as I am getting this warning as well now You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
yeah you can't new a MonoBehavior
I think the error tells it pretty clearly ๐ค
Lists confuse tf outta me, having a lotta trouble getting it to work lol.
Also, IndexOf will return -1 if the peData wasn't present in the list, and that would cause the index to be out of bounds
Nothing about it is list specific. You'd get the same error if you used an array
Arrays too lol, havent had to deal with one before. Let me try and remove the Monobehaviour and see if it works...
For example, if currentPEData was the first in the list, then currentindex is 0. And currentIndex - 1 is -1. So you are trying to access the list with a negative index which wouldnt work
The issue is that you try to access index +- something without checking if it's within the bounds of the array/list.
I don't think your first error at all related to this
Yah im sure its two different errors.
How would I catch that? make another if statement checking if it isn't first in the list? thats kinda the entire purpose of the if statement, to check if the currentindex is surrounded by one index above and one index below
A list has a Count property telling you how many elements there are in the list. Check that you're resulting index is below that count and above or equal 0
Imagine an empty box for items. What will happen if you try to take out a 2nd item from that box?
You'll get brain damage.
Now try taking out a -1st item
Makes sense lol. let me see if I can fix that error.
I have the following code inside the update functions: RaycastHit2D raycastHit2 = Physics2D.Raycast(-transform.up, transform.up); Debug.DrawRay(-transform.up, transform.up * Mathf.Infinity, Color.blue);
Hmm, I am having trouble getting the Class PrismEyeDataArray to work. If I try to take away monobehaviour I get
'PrismEyeDataArray' is missing the class attribute 'ExtensionOfNativeClass'! and I am confused on how ExtensionOfNativeClass works...
With monobehaviour on I'd need the add component method, but I don't know how to use that either lol.
However it is not drawing the raycast
It is the only code in the entire script, as I was testing it. Could Universal rp be interfering with it?
You toggled gizmos in editor?
uh you need a start point and direction
ithink
I didn't touch it, do I have to toggle something?
It's on the game view window, top right corner
this one for game view
Is that how it looks nowadays? Didn't update for some time
scene view yea
alright ^^
But yeah, thinking of the most stupid solution since mistakes are more often than not
Oh yeah, that's on, I was checking if there was something in there I might have deselected
Doesn't seem to be though
I made a brand new project, put a square sprite, gave it a script, and put the 2 lines of code into the update function
Still no drawing
Yah I'm lost. IDK how to get the PrismEyeDataArray class to work. Idk how to remove monobehaviour and still get it to work.
If you put it in Update, it's gonna run every frame, which shouldn't be an issue, but is probably not necessary
I just did it to test it, I don't know what else to do
Wdym by "work"?
If I try to remove monobehaviour on the class I get this error 'PrismEyeDataArray' is missing the class attribute 'ExtensionOfNativeClass'! Which seems to be inaccessable due to its protection level.
Where do you get the error?
Is it assigned as a component?
If it doesn't inherit from MonoBehaviour it can't be a component.
That's what I'd trying to use for 30 minutes before I came here ๐ญ
Sorry, I honestly have no idea wtf monobehaviour or ExtensionOfNativeClass does. So I assume not. lol
It's powerful, but it doesn't "understand" what it's saying, that's your job :p not that easy to use
chatGPT isn't really useful if you don't know what to ask it
Are you sure you want -transform up as the first parameter?๐คจ
I did say you're putting a direction where it should be a start point @static crown
I just want to create a new PrismEyeDataArray in the code, but MonoBehaviour is cucking me
wait...
At this point I recommend doing the beginner coder pathways on unity learn. Also move your question to #๐ปโcode-beginner
It could be an asset that used to be ScriptableObject
Chatgpt wrote that code btw :/, lemme try something
At least in this case I wouldn't blame chat gpt๐
@hexed pecan Can ya explain Osmal? both scripts are on the same object
huh draw line gives you specific points
I think its float.maxValue
Your script probably needs to inherit from MonoBehaviour.
Nevermind the ScriptableObject thing, it's probably not the case here
Mathf.Infiinity is capital I
Yesh
Anyways, thank you guys
I really thought it was gonna take 4 hours to solve the problem ๐ฅน
@hexed pecan Thats what I had at first, but I get this warning You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
In this method
private bool isMinimum(List<PrismEyeDataArray> peData, float currentPrism, Vector3 eyePos) // Somehow needs to be called multiple times to double check it is the correct value?
{
PrismEyeDataArray currentPEData = new PrismEyeDataArray(currentPrism, eyePos);
peData.Add(currentPEData);
peData.Sort(); // IDK I think it should sort the added values so it can bracket easier?
int currentindex = peData.IndexOf(currentPEData);
if (currentindex < peData.Count && currentindex > 0)
{
if (peData[currentindex + 1] != null && peData[currentindex - 1] != null)
{
if (peData[currentindex].eyePosition.x < peData[currentindex + 1].eyePosition.x && peData[currentindex].eyePosition.x < peData[currentindex - 1].eyePosition.x)
{ Debug.Log("Is bracketet and is minimum"); return true; }
else { Debug.Log("Is bracketed, but is not minimum"); return false; }
}
else { Debug.Log("Is not bracketed // Error is logic."); return false; }
}
else { Debug.Log("Currentindex is not within range..."); return false; }
}```
oo shit thats fancy
Please use the cs tag for correct coloring
You are indeed trying to create a monobehaviour with the new keyword.cs PrismEyeDataArray currentPEData = new PrismEyeDataArray(currentPrism, eyePos);
IDK how to get around that?
Do you need PrismEyeDataArray as a component that is attached to a gameobject?
(A monobehaviour)
Prob not? Can I just remove it from the object and then remove monobehaviour?
Yep
@hexed pecan Sweet think that fixed my issue thanks! Now I gotta fix the logic of my method. Getting an Index out of Range exception.
What value does the weight have?
the value of a curve
an int from 0-1
wait nvm im dumb
it's just an integer lerped from 0-1
there is lerping involved but not with angles
An integer can't be "from 0-1"...
an integer can only be 0 or 1 nothing in between ๐ค
*float ๐
I've been working on a 3D pathfinding system that uses a modified version of the A* algorithm. One of the challenges I've been having is finding the best data structure to use for the "Open Set" for the algorithm. I'm currently using a weird implementation of a Skip List that I wrote, as it is the fastest thing I have tried, but I don't think that it should be in this use case and am hoping I can still find something better to speed up the pathfinding a bit more.
Does anyone have any suggestions or resources on data structures that might be better than a Skip List for this type of application? The main bottleneck in my pathfinding is maintaining the sorting of the open set and I'm reaching a point where there aren't many place left I could speed up the pathfinding other than using a data structure that could do this faster.
Ok. First make sure that it really is changing from 0 to 1. Then check your curve and make sure that it takes ranges 0-1.
Something like a quad tree maybe? Aside from that, you could make it async(as in over several frames) and or jobified to further boost the performance.
well it does, if i aim down sights while not reloading it works fine
it only is a problem when you aim down sights while an animation is playing
once you finished aim down sights its normal
like the anim viewmodel goes crazy
Right, I intend to work on multithreading the system down the road but right now I'm trying to reduce the total work necessary to calculate a path before doing that.
I guess what I mean in my question is that a lot of data structures that maintain an ordering allowing you to get a minimum element by some priority (generally called a "Priority Queue" I believe) will do their reordering when an object is inserted.
This generally isn't a problem for 2D pathfinding, as generally a node may only have up to 8 neighbors (accounting for diagonal movement). In 3D and using an irregular octree to create nodes, some of my nodes have many more than 8 neighbors, as there are more directions and in some cases many (some power of 4) neighbors in each direction.
This means I insert nodes to the open set exponentially more often than I remove them, compared to in 2D. I think some data structures (like a Fibonacci Heap) instead handle reordering when the minimum element is removed, rather than when they are added and/or take advantage of other properties of relations of their nodes to speed up the reordering. I'm just not sure exactly how everything works for each data structure and I'm not sure what would really be the best in this use case and am running out of ideas lol.
I'm going to assume that this is best placed here. I'm trying to fill a GameObject array in a non-MonoBehaviour script for my applied programming college class. I'm able to call the function, but then this happens. I wanted to hard code the arrays since our final project should have most of data stuff in the non-MonoBehaviour script
Sorry, I just saw the "no reposting to other channels"
Honestly, I'm not sure you'll get an answer here. It sounds like a topic for a serious research paper in the field of pathfinding implementation. Definitely not something an average game developer can help with.
Simple compile error on line 35
your code there makes no sense
Right, I was just hoping I might get lucky and someone here that had some experience in the area might be able to point me in the right direction. I haven't been turning up much on my own. I appreciate you taking the time to respond!
I just use minheap, even 10^9 nodes it can pick up min within O(30)
I have never consider the case branching factor is very large
KibblesItems FillItemArrays(); < what does this mean? It's nonsensical. You just have two things separated by a space. This isn't valid C# code.
Also @leaden sonnet your IDE is not configured
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
You need to configure it so you can see errors and get autocomplete
apparently #๐ปโcode-beginner message
I have a KibblesItems public class, and I am trying to call a function from it but it doesn't derive from MonoBehaviour. I work on a school computer. I am trying to call a function that puts prefabs into their appropriate arrays in my GameManager public class deriving from MonoBehaviour
you can't call classes like that
You need a reference to an instance of the object.
Then you need to use the dot operator: .
then then function name and the ()
what you have is:
- A class name (not a reference)
- no dot operator
Non-Monobehaviour scripts can't attach to objects though right?
MonoBehaviour or not is not really relevant here.
i don't see how that's relevant
you still need an instance of it to call a method on it
You can create an instance with the new keyword
oh right omg
without an instance I'm not sure what you think you're filling the arrays on?
People don't like my professor so forgive me for my blotchy understanding
Just data to be held in a non-MonoBehaviour class
the class doesn't hold any data
the class is like a blueprint for instances
the instances of the class hold data
idk what that means
the instance IS an object
everything in C# is an object
it's an object-oriented language
I understand the object-oriented part, sorry, it makes sense that I need to make an instance of the class for anything to happen
KibblesItems a = new KibblesItems();
KibblesItems b = new KibblesItems();```
^ this creates two instances of the class. Each instance has its own independent data
How useful is it to learn that academically? I learnt everything on my own, so I don't have much perspective. I would argue that you don't need to know how to make a hammer to be a carpenter, although it could help. Thought?
Really just puts more money in my college's pockets. This professor of mine is...not organized or helpful much.
I feel like what I learned in college about programming and how computers and software work was invaluable but I'm sure it can be self-taught as well
I actually used Unity Learn to refresh on concepts and learn new ones because my professor doesn't make sense
We will struggle conceptually and he just insults us
๐คทโโ๏ธ
doesn't sound like a great teacher
SCAD Atlanta is sad
I'll just say that
Especially the game dev major
anyway I'm venting in a code channel lemme play with the instance thing, thank you
are these teachers getting degrees in cereal boxes?
I don't doubt that, although for me it's really about what I'm spending my time working on, learning, or doing stuff. Both are valuable, it's hard to tell what's best
Major job of Professors is not teaching but research, usual
SCAD will be nice to have on my resume
I agree, higher education gets weird, although I can't relate to the US system the same thing was true in France, teachers were knowledgeable but not that good at transmitting that knowledge. Anyway, thanks for the reply, not really the right channel, sry about that
You were 100% right on what my problem was, but now I'm having an array length just not get set
OOP you mean? I'd say it's one of the minimum requirements for a junior programmer. You don't need to learn it academically. There are enough materials available on the internet that make it clear even for a child.
never mind same instantiation problem
is there a way that I can get my list of users in firebase and save their data in UGS Cloud Save?
maybe you'd have to write a custom script to migrate
Not really about OOP, more about the exhaustive aspect of academic learning. For instance, I learned (kinda) late the difference between reference and value type. Is it useful? For sure. It really made me rethink conceptually my approach to coding (in the context of Unity at least).
Would I have been receptive to it in a class where the uses of that concept are described abstractly? I'm really not sure.
There's probably a LOT of subtleties that I neglect while coding. I'm just not sure how important it is to know them all
this already gives you decent Object to work with
https://firebase.google.com/docs/auth/admin/manage-users#bulk_retrieve_user_data
And apparently in Unity Cloud
Use Cloud Save to store any kind of player data you want.
I tried watching tutorial on Youtube that do explain those concepts exhaustively, and I'm not sure how useful this has been for me.
If you're just letting that info go through your ears, there's definitely no much point in it. It is best to learn while actually doing something. For example, when you're implementing some code in your project, inspector every line carefully. Do you really understand the meaning of that syntax/function/type? Let's say you see a Vector3. Why is it colored differently than other types? What is it a struct? Why is it a struct and not a class? Once you start asking and researching these kind of questions, you'll really start learning. Then also try to experiment on your own given the acquired knowledge. Can you make a class vector? What does it imply? How is it different?
Stuff like that.
Makes a lot of sense. I started with the pragmatic approach "how do I code something that does this?", and lean more and more to an abstract one "how does it work?" "could it work differently?". I think it's the best approach, since I always felt at my level of understanding, which keeps it compelling.
That being said, I'm a bit envious of some of you guys that understand it more thoroughly because of the basic concepts taught in school, but that could be me being biased, and a simple lack of experience.
I haven't learned anything about software engineering in school. Everything I learned is self taught. So if I could do it, so can you.
Good to know, maybe it's a "believe in yourself" kinda deal aha.
Anyway, the biggest hold back I think I have from self teaching is the lack of feedback, so it's pretty cool this kinda of "meta" discussion about coding, I appreciate it, thanks ๐
Do go through the C# manual if you haven't yet though. Even if you don't understand parts of it, you'll know where to look in the future. Ideally you want to have at least a general idea on the existing concepts.
Noted, bigger tool belt for more adequate tools, makes sense.
float2 == float2 produces a bool2, just use .Equals or similar
oh so i need to do:
public bool Equals(in Edge edge)
{
bool2 flag = _a == edge._a;
bool2 flag2 = _b == edge._b;
return flag.x == flag.y == flag2.x == flag2.y;
}
``` ?
not really sure i understand the syntax of their bool2 type kinda odd
Declaration
public bool Equals(object other);
DescriptionReturns true if the given vector is exactly equal to this vector.
Due to floating point inaccuracies, this might return false for vectors which are essentially (but not exactly) equal. Use the == operator to test two vectors for approximate equality.
Docs suggest using == instead because of the approximate nature
where you get that quote from
unity usually implements override for their comparisons anyway
so a==b for vectors should be fine
as would equals
why In?