#💻┃code-beginner
1 messages · Page 168 of 1
maybe this is why?
the green line is probably the size
yeah that fixed it
@swift crag ur system works well enough but when i decide to switch to using mouse, it highlights two at the same time
how could ufix this?
It's a non-trivial problem. I haven't figured out the best way to handle it.
You could auto-select whatever your mouse cursor is over, but then that causes headaches for people using both the mouse and keyboard to navigate the UI
You can make the "hover" and "select" colors different, at least
I use these tints, for example
fair enough
unrelated, sometimes when i want to load a scene, it doesnt load the scene i want to go to and just loads the current scene instead. any idea how i could fix this?
well, how are you picking which scene to go to?
and are you getting any warnings in the console?
no, nothing is going wrong in the console its so weird
it works fine the first time i go somewhere but the second time it breaks
i'll record video
show me your code.
hold on
i need to test something
figured it out
i had a script that broke it because i didnt want to keep going between scenes
can I somehow disable the influence of a parent GameObject? I dont want the child object to move with the parent object
then don't parent it
you can unparent the child during Awake if you need this to be in a prefab
that's what I do in my game -- I have a ragdoll that can't be parented
I make a new "root" object, parent the entity to the root, and then parent the ragdoll to the root
(the root is there to make it easy to destroy everything later, but I could also just keep a list of game objects that all need destroying)
@swift crag the issue still seems to be happening in my pause menu, its loading the wrong one for some reason. despite being set to "HubWorld", it loads "menuscreen" for somer easoon
the debug even says its going to hubworld
but it goes to the home screen and idk why 😭
where is that being logged?
the code you sent doesn't have any log statements in it
so it's possible that something else is also trying to load a scene
public class ExitToSceneButton : MonoBehaviour
{
public string sceneToLoad;
private FadeInAndOut fade;
void Start()
{
fade = FindObjectOfType<FadeInAndOut>();
}
private void OnEnable()
{
FadeInAndOut.FadeInCompleted += LoadScene;
}
private void OnDisable()
{
FadeInAndOut.FadeInCompleted -= LoadScene;
}
public void Click()
{
print("loading to " + sceneToLoad);
StartCoroutine(fade.FadeIn());
}
private void LoadScene()
{
SceneManager.LoadScene(sceneToLoad);
}
}
my button code
log it inside LoadScene instead
I'd also log when you subscribe to/unsubscribe from the FadeInCompleted event
notably, if you have two ExitToSceneButton components in the same scene, or two exist anywhere, both will try to load a scene
Just realised, there are two buttons that try to load it
since all they do is respond to FadeInCompleted
I have similar behavior in my own game, but all scene loading is done by a singleton GameController
That makes so much sense now
You ask the controller to enter a scene, and it starts a fade effect
then when the fade is over, it loads the scenes
i need to make it log a warning if it's in the "loading" state and gets asked to load another scene
i think that happens if I mash the "start" button..
i think i can just make it subscribe once its clickjed? that would work better
obviously not as good as a proper controller
That's an option, yes. You can unsubscribe in both OnDisable and in LoadScene
but like i think that would avoid the issue
unsubscribing excessively is fine
how can i delete a player input from the game? lets say if a player wants to leave or whatever
i have this player input manager thing
and i want the player input to get destroyed if it exits to main menu
a script would need to do that
my first week using Unity....I'm very confused as to why my GameObject can be detected using the OnPointerEnter / OnPointerExit....but my UI Buttons aren't....unless I place them at the edge of the screen, then they only show up in the debug info once I move my cursor on/off screen. I'm considering just changing all my Buttons to GameObjects at this point
gameobjects cannot be detected like that
it says there are player join and leave messages though?
gameobjects can only be detected via components on them
UI objects use IPointerEnterHandler and IPointerExitHandler instead
https://docs.unity3d.com/2017.4/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html
Yeah I tried that method and it just didn't work for me, but then I am very new
Unity’s UI system is kind of weird
oh wait this is for Game Object though?
I wanted to be able to detect when I hover over buttons
No. these are for UI objects.
You implement an interface and then add the method that interface calls for.
'//Attach this script to the GameObject you would like to have mouse hovering detected on' thats why I was confused I guess
Alirght I tried unparenting a GameObject using transform.DetachChildren() the script is on the parent and it does not seem to work, the child stays a child anyone know why?
components have logic/script associated with them
This is for UI objects
which are game objects
like everything else
gameobjects cannot do ANYTHING without components
ah, yes, I was being unclear there.
yeah, hence why I had to put scripts on them, I got that
the two things we care about are...
- UI objects: things like Image
- Physics objects: things with physics colliders attached to them.
That is the distinction.
hence why we have GraphicRaycaster and PhysicsRaycaster
i’m not sure that the two are mutually exclusive
You could mash both together, yeah
let’s not confuse the man
So let's start with the basics....I put a UI Button into the project, then to make that detectable by cursor what script do I use???
u have a gameobject that is a child of a child of a child… of a canvas. This gameobejct is tied to the UI. This gameobject can have components in it that work with UI
you also have a gameobject automatically put into scene called EventSystem. EventSystem takes in inputs, and manipulates UI elements. Such as causing mouse position to activate buttons
got that
EventSystem is automatically added when you add a canvas
somebody help me?
the object not accompanies the character's hand
Ok, now the gameobjects in the canvas use special UI only components, like button, rect transform, and grid layout group to do their thing
Button is the one responsible for making a button.
yeah well I know how to make my game object a button, I've done that haha
but I wanted to add a UI Button into the game, which I can hover over and detect in the console
my debug only shows my cursor entering/exiting that button when the button is placed around the edge of my canvas
and I'm like what
so this was frustrating me and I built a new 'button' using a blank GameObject, and for some reason that could be detected anywhere when I gave it the script
so for this, it sounds like you need to use OnPointerEnter
which needs to be on a class derived from Monobehaviour, implements IPointerEnterHandler, is on the gameobject, and has a function with the exact signature:
public void OnPointerEnter(PointerEventData eventData)
which is in the UI space
ie it has a rect transform
(so, attach it to the same object as the Button component)
if any of those 4 requirements are not met, your function will not get called
can I just send you a video of what I am experiencing because it probably isn't clear
i can’t rn
I have a GameObject button that is detectable in the console
I have a UI Button that is detectable in the console, but only when placed at the edge of the canvas
so I am trying to figure out why it is only detectable when placed there
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What should I use to make animation of 2d objects? Simple ones like rotation.
Okay, this looks fine. It implements the right interfaces.
what can cause a FindFirstObjectByType not work ?
i am loading a scene and trying to get a object that exists, but unity isnt finding it, i wonder why
When you click on the button, does it visibly change color?
you can change the colors in the "Button" component. The defaults are a bit hard to see.
What type are you searching? Why are u searching for a type?
they're trying to find a unity object in the scene
It used to. Now it doesn't
(generally a MonoBehaviour)
a custom script type
Okay, so you aren't getting UI input at all.
Is there an EventSystem in your scene? You can search for it in the hierarchy
t:eventsystem
punch that into the search box in the hierarchy window
yeah
Post the line u are using to search for it
Show me the hierarchy with the button object selected. Include all of the other children of the canvas -- let me show you an example...
looks like the script is only awake after the find
I have "Choice Entry(Clone)" selected
gonna have to see some code here
Post the entire function (if its not long) where you try to find it?
you mean like this?
I still don't really understand what he is searching to need anybytype.
to find an object
public void Restart()
{
SceneManager.LoadScene("Game");
Time.timeScale = 1;
MainMenu mainMenu = (MainMenu)FindFirstObjectByType(typeof(MainMenu));
mainMenu.StartClick();
}
Yeah but whats the goal
i didnt find a better solution for now to get the reference
it's been a complete mess, just been experimenting with everything
You can check if this is the case by making a new empty canvas
but now my mind is at 'why do the butons not light up like they used to'
Is that a script?
copy just the single button onto it and deactivate the original canvas
You are searching for
yeah I should do that Fen
this will ensure you don't have any other UI elements in the way
the function is inside a script yes
Children draw in front of parents, and later siblings draw in front of earlier siblings.
wait ik why it doesnt find it
A common error is to have a huge Image element that's blocking all of your buttons
the code is prob executed before the reload
this is what I was worried about
I'll try a blank one
Correct.
i need to do stuff to a objetc that is loaded, so I can only execute the code after the scene loaded
Is this on an object in the DontDestroyOnLoad scene?
I fixed issues my scene loading issues like this, search happend before object got loaded.
the game object wont show up unless im click on it
can i just make a load scene with params, then in my Menu read the params from SceneManager.sceneLoaded ?
You can
i need to look how the scene params work
You can also use the same DontDeleteOnLoad object to store data
nope
This object is getting completely destroyed by the scene load
Yeah
Guys i've a question, my game starts lagging when multiple collision occurs, how can i optmize collision?
yes
so it seems kind of pointless to do anything in it
Instantiate(enemyDiff1[0], (activeRooms[0].transform.position + dungeonSpawns[Random.Range(0, 9)].position)); why does this not like the addition of the the two transform.positions arent they both vector3's
that's not the problem
What does the error say
read the error.
it says cannot convert vector 3 to transform but when u hover over both they both say vector3
Maybe remove transform?
Okay, and do you see a version of Instantiate that takes an object and a Vector3 as its only parameters?
is there any way to apply a physics material through code?
this will produce an error because the function does not want a float
How many collision are we talking about here ?
how?
Reference the Collider and apply it?
keep a reference to material as well
bru my messages drowned
I think he has issues with whatever code he runs in the oncollision (trigger or enter)
@swift crag I'm having a moment....I just copied the button onto a new canvas/scene and I can't see the button? I probably need sleep
like a lot. If you know vampire survivor you get the idea @charred spoke
@faint osprey
Look at the documentation. See the only form of Instantiate that has two parameters, and see what types those parameters are. Is that the version of the function you want?
"Canvas" and "Scene" are two wildly different things, so we need to know which one it is..
yeah I just realised I dont have a canvas LOL
Create a new Canvas from the GameObject menu
Then you can attach a Button to it and try interacting with it.
Well I suggest you learn to use the profiler and see what exactly from the collision is taking up time. If its just the collisions you can try using a simpler collider, or get into DOTS
@charred spoke so you kinda get the idea, don't mind sprites ahah
This does not seem like a lot. Check your profiler
kk @charred spoke ty
[SerializedField] PhysicMaterial physMaterial;
[SerializedField] Collider theCollider;
public void ChangeMaterial()
{
theCollider.sharedMaterial = physMaterial;
}```
ok thanks will try
how can i make a gameobject visible if its overlapped by another gameobject?
turn the renderer on?
it is on
so start it off
change it's position relative to the camera
Is that object even visible. Is something in front of it or is it just invisible?
@swift crag now it's just the blue screen. I see the button in the window but not in game mode
something is infront of it
How could I give a cone of light a hitbox that travels as far as the light itself? So like things know if there's a flashlight being shined on them or something.
So then put that thing behind it instead
how lol
use a mesh+collider or physics cast rays in cone shape (takes some math)
by changing the position of the object so that it is no longer in the current position but a different one
irl, how would you make something visible if it was behind something else?
put it infront
so do that
i tried changing the z value
doesnt work
I’d have to see what you’ve done. Perhaps your button is positioned wrongly
can physics raycasts find everything within an entire cone instead of just a single point?
yea if you put it in a loop
you can create a cone shape from multiple rays
how comes when I first started all of this I had no problem, and now I can't even do the basics 😂
Is it visible if you disable the blocking object entirely
This is becoming more of a #📲┃ui-ux problem, so you should ask about further issues there. The channel also has some resources pinned
am I dumb
You could also use Dot Product with certain angle, and then Raycast to check obstacles in way / length
Then it's definitely blocking the object and you'll need to position it further from the camera
but im changing the z value
You're working with sprites right? Change the values here.
are you actually moving it further from the camera
and not closer to it
Your background might be sorted higher.
oh that worjed
dub
Ok I'll try that out
the z may not be what you want. move it towards the camera
ui problem
That should only be checked if the objects are at the same depth, but it seems like that was the case
wdym background was sorted higher
Nah with sprites the sort order takes priority over depth.
I thought the position was respected with an orthographic camera, I'd need to open up Unity to double check
Don't think so.
But I haven't done much 2D so it's entirely possible I'm wrong
Could be wrong.
Position is used.
what are u guys yapping abt
Sprite sorting is kind of a whole thing. Basically your background sprite was always on top because reasons. Changing the sort order of the cracks is telling Unity to always render the cracks ABOVE the background.
The red sprite is physically behind the white sprite, and its "Order in Layer" is 1
interesting
Weird. So, position is checked before layer, but not before order in layer? That's kind of... backwards, isn't it?
counterintuitive init
sorting layer also makes the red square appear in front of the white square
Here give this a read.
https://docs.unity3d.com/Manual/2DSorting.html
is there darkmode on unity docs
Ah, I could be seeing different behavior because this is the scene camera (in orthographic mode). I also don't do a lot of 2D myself!
Not without a third party extension. Also not a code question
lol that wasnt the first question i asked it was abt the topic
Sorting Layer and Order in Layer I believe is the highest priority of sorting you can do with sprites, then it's Render Queue of the material, and then it goes down to distance to camera.
Huh. That's like, the opposite of what I had thought it was for like, years.
That's also the opposite of what I expecting, haha
One of these days I should actually try to do something in 2D so I can understand how it all works
I've only ever been interested in dealing with things that overlap
so I guess the misconception was just as good in that case
Nah you probably want to do it this way. Imagine something doesn't sort correctly even with proper Sorting Layer and Order because it was 0.001 units closer to the camera.
It would be absolutely mind numbing to sort anything in the transparency queue with a perspective camera.
Also @little oak, consider using this component. It'll make sorting complex sprite objects/characters a lot easier.
https://docs.unity3d.com/Manual/class-SortingGroup.html
guys, do you have any good updated tutorial on how to use unity profiler?
yes: the documentation
consult the "Profiling in the Unity Editor" section of "Profiling your application" for info about using it in the editor
so how would one typically offset a camera in 3rd person so that it appears over the shoulder instead of direct center of the player
back and to the left..
my player has been destroyed, but stuff in the playerscript is still running and idk why
@rocky canyon they usually use child object?
destroyed or disabled? a destroyed script isnt gonna continue to function
thats a pretty static and mechanical feeling way
id use cinemachine
has a built in camera that has orbits
i like static lol u havent seen what ive been through xD
if ur loookin down on the player the camera goes closer.. if ur lookin up at the player hte camera goes closer..
destroyed, i have no idea how this keeps happening
In this video, we’re going to look at how we can set up a third-person camera using the new Aiming Rig of Cinemachine 2.6, and how we can use Impulse Propagation and Blending to create additional gameplay functionality for our camera controller.
Download this project here!
https://on.unity.com/36nVNzt
Learn more about Cinemachine 2.6 here!
htt...
that also means any small wiggling of player position immediately gets transmitted to camera.
you want some amount of damping
That is truly not our problem
check out that video, its really not hard.
but if want a player locked camera u can use a child yea
sounds like you just don't understand it and instead of trying to learn how to properly use it, you're just complaining about it
we provided you a simple camera technique. If you just don’t like it, then you should figure out your own way.
not really complaining my boy just feel like the only person not using it
how would I go about creating an "IsWalking" boolean that can detect all WASD inputs so that I can optimize my code
I don’t use it because I am in 2D
the main camera stays around just like it normally does.. (only with cinemachine you use the virtual camera) and the normal camera snaps to the virtual camera's position..
I think you subscribed to the sceneChanged event and forgot to unsubscribe when your object was destroyed.
same way you create any other variable
the virtual camera is what controls all the cam movement
how would that optimize code in any way? 🤔
but I also needed to make a whole big system for my camera to work. Probably about 1 month of coding on my camera, with all the little knick knacks.
yeah i just checked that
Vector2 moveInput = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
bool isMoving = moveInput.magnitude > 0;```
because then instead of saying
Input.GetKeyDown("w)
Input.GetKeyDown("s")
Input.GetKeyDown("a")
Input.GetKeyDown("d")
i can just say IsWalking and its yeah
same, i built my entire camera system, its a god cam, looking down and panning etc
and YET i still used a cinemachine as the camera ;D
hehe thats cool
yeah no. that's not what you need. you should learn how to use Input.GetAxis instead of querying each key individually
thanks
i was looking at warframes camera and noticed the offset was pretty much a child
but ya warframes definitly pans in an out the further you go up down
ah yes, suggesting a better alternative when the point of your question was to "optimize" your code is definitely being rude 🙄
ya, thats the cinemachine follow camera setup
the farther up or down the camera the smaller orbits it uses
My system is for a maker style game. It mostly has logic on gameobjects that can interact with game world. These objects either 1) set camera to target them, 2) prevent camera bounds from crossing them, or 3) tell camera to smoothely pan to the opposite side of a wall.
im finding if a child is active to turn on movement, is this performance wise bad
if statement no, GetChild maybe
I really like this system, because it really integrates camera into gameplay/game world
hey there, any idea on how to improve this? https://gyazo.com/24e509c91af1e2d1cbb75c95ede78821 While entering multiple collision game starts lagging. I'm trying to understand how the profiler works but it's tough
why not just put the movement component on the child that may be deactivated? then you don't need to do any GetChild calls or check if it is active since Update will not run when it isn't active
i just wish cinemachince code wasnt so long or id go into it
because you can use specific things/interactions to break/move these camera targets/barriers, to let the player effectively move the camera as a part of the game
lol cinamachince lite tm
my non-cinemachine camera scripts combined are easily 7000 LOC
im trying the same.. when i zoom in i want it to feel like ur using a telescope, (so zoomed in u get that little cam shake) zoomed out it goes away 😄
ur thinking of it the wrong way.. the cinemachine components just do what they do. (rarely do u need to get into that code to do anything)
u still declare a camera in ur own scripts (only u can declare it as a virtual cinemachine camera) and u then u can enable it, disable it, move it, parent it, or w/e
lol i like learning camera code though
i might change it and make it like a drone or hawk
anyway thanks for your help
Let's learn how to make a solid third person controller with a moving camera!
Jason no longer offers the course mentioned in the video.
👕Get the new Brackeys Hoodie: https://lineofcode.io/
● Third person controller asset: https://assetstore.unity.com/packages/templates/systems/third-person-controller-126347?aid=1101lPGj
·····················...
well its hard to find a third person camera tutorial that isnt cinemachine, but brackeys has one i guess!
third person camera is hard because walls will get in your way
we went through the entire N64 era without devs figuring out how to stop walls from obscuring your view
cinemachine collider does ok job but can be improved
learn from what came out in the end. don’t repeat their struggle and still shitty cameras
ya, its hit or miss even with the cinemachine collider
u pretty much need to design ur level in a way that compliments what ur camera can do
super mario 64 was okay
lol, back when the camera might as well been its own character
hitting all those yellow buttons just to get a decent angle to walk forward
Pressing the yellow arrows for the prefect view was its own game . . .
lol, this guy gets it 😄
when those buttons gave out on ur controller, it was a whole different level
Im not familiar with the 2d physics engine but reading online it seems that you have too many moving shapes or one large collider overlapping too many shapes. What colliders are you using ?
I understand the basics of Unity C# but i can't really put any of it to practical use, I don't know how to combine anything yet
What do I do
Any easy exercises that could teach me to connect stuff together?
yea, ^ what type of game do u wanna make.. start small.
the best advice anyone can give to someone who has already learned the basics is to just start making shit
ima be real ive tried starting small and its too big hahaha
Welcome to the John Lemon’s Haunted Jaunt: 3D Beginner Project! In this project, you won’t just discover how to create a stealth game — each of the 10 tutorials also explains the principles behind every step. No previous experience is needed, which makes John Lemon’s Haunted Jaunt the perfect start to your journey with Unity.
yeahhh judging by that thumbnail that is wayyy too advanced
unity learn is still a good resource, for putting the stuff together
i need something that is like, the bare minimum, even if its a tiny snippet of code, a very easy challenge
just something to help me connect the dots
i know what booleans are, i know what strings are, i know it all, but i cant seem to put them together in my head
Just like make game
but what game??
whatever you want
You can try whatever you want. Just don't expect to finish something complicated
this is not actually "understanding the basics" then. you know a few random things but don't actually understand it yet. if you really need something that basic, then go through a structured course that teaches the concepts you need to understand in a way that actually makes sense. don't just do a bunch of random disjointed tutorials
i'm using polygon collider for my player and same goes for enemies. Now i've put that enemies won't collide between them and it improved for sure. But it is still laggy if there are 40-50 enemies
https://gyazo.com/4df9e79f296858b548ac68aa1161b93f here's the enemy inspector
Don't use Polygon colliders, use a basic collider
now i've tried reducing the fixed time update from 0.002 to 0.003
there's no reason these characters can't have box colliders
but then hitboxes aren't gonna be accurate no?
^ or capsules
just asking
how accurate do they need to be?
Why do you need hitboes to be accurate
do u have a finger damage modifier?
not yet eheheh
usually 2 colliders are enough for anything
i'll put box colliders then
a body and a head
You'd only need that if they actually have different behaviors
Do your characters have different body parts that do different things when they collide with things
no not yet tbh, just wanted to add punch animations for enemies
but it shouldn't affect hitboxes
irrelevant
hello, i'm trying to save data in a file for my game using application.persistentdata, but it keeps telling me that there is no authorisation, how do i fix this
fix the path make sure its correct
don't crosspost. i just wound up answering this over in #archived-code-general
and another thing. Is there a way to make it so i don't have to use 2 different colliders for one object if i want it both to collide and trigger? Right now my enemy object has two collider. One is set to is trigger and the other is not, so that the hitboxes have some sort of physics collision. Question is, is there a way to use just one to use less resources?
while achieving the same result
it depends. what is the trigger collider used for?
nothing wrong with really doing that tbh
enemy colliding with the player and dealing dmg @slender nymph
@rich adder i wanted to optimize the game a bit, and putting 1 less collider for each enemy would've improved a bit maybe
and why does that need a separate collider? why can that not just be the non-trigger collider
because then enemy overlaps with player
they can sit on top of eachothers
not good looking
difference is prob negligible , you can look into the physics class queries
Just put them on a layer that is set to not collide with itself
you do realize i am not suggesting to make the player's main collider a trigger, right? so that would be the opposite of what you just said
non-trigger colliders do not overlap unless they are being moved without physics
@polar acorn ye enemy cannot collide between themselves if that's what you're saying
so if i put on capsule collider 2d on the enemy object and set it to trigger it won't overlap with my player object?
@slender nymph
what do you think "non" means in "non-trigger"
but i'm talking about "is trigger" colliders
and i asked you why you need one in the first place
to detect collision between enemy and player object
why can that not be done with the collider that is not a trigger?
(#💻┃code-beginner message)
hi did anyone know why this is not installing?
this is a code channel
its downloading for 10 hours
This is still a code channel
i restart unity and install the lattest version of unity
so i just use oncollisionenter @slender nymph ?
where can i ask
yes you can use that when you expect two non-trigger colliders to collide. then you won't need a second collider on the object that is just a trigger collider for doing exactly what the non-trigger can do
Also @late bobcat you can get away with the simplest collider a circle
For this type of game
Try and see
Computation wise it would be capsule -> box -> circle
where circle takes less resources i guess
Yes
aight
Cant get simplier that a circle
games looks supersmooth atm and i can still optimize stuff @slender nymph @charred spoke 😄
StartCoroutine(sayHi("hi", response=>
{
Debug.Log(response);
}));
public IEnumerator sayHi(string greeting, System.Action<string> callback)
{
Debug.Log(greeting);
callback("hello");
yield return null;
}
Is there easier method than this to pass and return value for coroutine, or how i can improve it?
i'm using cine machine and moving my mouse down make the camera goes up how do i fix this.
literally no code behind it
literally no code behind it
then why ask in a code channel? #🎥┃cinemachine exists
this code isn't returning anything. There's no clear reason this code should be a coroutine at all either since there's no delay going on.
it's just a minimal example
This is reasonable, although the syntax is ugly in that StartCoroutine line, yes.
since coroutines cannot return objects and they also cannot have out or ref parameters then a callback you pass to the method would be the ideal way to get data out of the coroutine. or you can store stuff in fields, but that isn't always ideal
You can create the anonymous function ahead of time
random range 0,3 will have equal same chance for 0 1 and 2 right
You can also pass in a method instead of an anonymous function
StartCoroutine(sayHi(MyMethod));
how it acts depends on if its float or int
What do you mean "a weird way of calculating"
but its even chance of 0, 1 and 2 for a Range(0, 3)
its exclusive of the upper range, but inclusive of the lower
because when im splitting it in half it starts getting confusing
as i still need add 1 for calculation
thank all who responded, i will debug.
now Random.value is better for a lot of things though
Explain what you're trying to do.
that will not give you a reliable weighted chance
i have only 2 values defining weighted chance
the cube moves left to right continously and when i jump it sometimes glitches in the wall and gets stuck
anyone knows why? setting vel to move it
have you checked if OnCollisionEnter is ever called?
you've got several debug.log statements commented out
Oh yeah theyre for test, yes the direction gets changen, OnCollisionEnter is called as usual
okay, so then this part:
the cube moves left to right continously
is not a problem?
It sounded to me like you were saying the cube never changed direction
if you ever get stuck in the wall or against the wall, OnCollisionEnter won't get called repeatedly
check what your direction is when you're stuck
one sec
-1 is left +1 is right for understanding
check if player doesnt move then change direction?
Yeah, so you're against the wall, but you're also moving towards it
I noticed that you switch directions even if the collision was from below. What if you're hitting the white blocks?
can somebody help with this error?
using Unity.Mathematics;``` both of these using statements have a `Random`
ur script doesn't know which one to use.. the error tells u how to fix it..
decide which one u want to use and call it
UnityEngine.Random.Range(1,101);
or you can set the entire script to use a certain one..
using UnityEngine;
using Random = UnityEngine.Random;```
oooor, just get rid of the mathmatics namespace.. unless ur using it
your IDE might have imported Unity.Mathematics at some point
thankyou for the help this fixed it
i hate when it does that
like, whats even good in that namespace?
https://gyazo.com/fa513b63507761a5d3e9aee06f640a35 guys why am i getting "An object reference is required for the non-static field, methor or property 'Animator.SetFloat(string, float)'?
what am i doing wrong 🤔
you need a instance of animator
so use GetComponent to get one
Animator myAnimator;
myAnimator.SetBool...
or use lowercase animator looks like you already got a field for one
it's got some good noise functions!
ohh true true
i'm dumb
Hey guys, So it seems I've run into a bit of a problem: I'm writing a script to detect figure out whether a gameObject is colliding with something from a certain direction (the ground and walls, namely). However, the ground and walls are on the same layermask due to them being part of a tilemap. This apparently causes a bunch of problems with raycasting, as the cast doesn't know the difference between a wall and the ground.
Is it possible to detect the ground seperately from the wall (maybe using a Physics cast instead of Collider2D cast now that I think about it)?
Can you place them on separate tilemaps?
I don't think that's possible, since the ground can be the wall, depending on which angle the gameobject is colliding with the tilemap from.
For example, a corner could be both the ground and the wall, depending on the collision.
Hello! I need help. I was following "Learn Unity Beginner/Intermediate 2023 - Code Monkey" and than I encounter an error. Basically I selected the wrong prefab and then when I trade it and put everything the right way it only interacts with the main prefab. Video: 2:48:30. Can anyone help me please? I already checked and I'm applaying the scripts on the prefab page(the right way).
Post the error and the video
Hmm, I see. I wonder how they handle that? Actually, couldn't you check the position of the tilemap to the hit point and determine which side it came from?
How would you implement that?
culd use seperate box 2d colliders and put them along the walls
and have an additional check on that when that edge-case happens
Technically that works, but makes working with the tilemap a lot harder (especially for larger maps)
But it works nontheless
can u get the centerpoint of the tile when u hit? i could think of another way, where u do some math to get the angle between the center point of the tile and the player.. if that angle is > than 45* or w/e (which would be the where the tile's corner meets) u could know whether u hit the top of it or the side of it
💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
❤ Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🎮 Play the game on Steam! https://cmonkey.co/kitchencha...
can u get the centerpoint of the tile when u hit?
Unfortunately not, since my tilemap's collider is just one big piece (due to a compositecollider without which there'd be other collision issues)
I'm guessing that means this wouldn't exactly work due to the tilemap's origin position
ya, i woudlnt know of a way to do it w/o having the exact center point of the tile, and the tile needing to be perfectly square
theres other methods tho
any clues?
Is the error you're talking about the "look rotation is zero"?
That's not an error, unless you're referring to a logic error. You'll have to post your !code so someone can help you look into it
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
🦆
are you using rule tiles?
i ask because one of those tiles looks not correct
hello guys! I'm doing like a spider man game first person game and i wanted to implement front flips. I used chatgpt but it was really buggy and it woudn't work properly. With this code, when I press "Q", my player does a front flip as expected but when its in about 180 degrees angle, it starts flickering a lot and sometimes when the flip is over im facing the wrong direction... can someone help me please? https://paste.ofcode.org/36BScLxvi5zJfaQgzafGYXU
No I placed everything manually (Including that odd-looking grass block for testing).
you should probably learn properly instead of using gpt
you have 2 different places where you are assigning the camera rotation, that is probably why it is acting like this. also using eulers might not work as expected here, rotation is stored as a quaternion. When you give it an euler, it converts to quaternion, then you convert back when reading as euler. It can give you different numbers that result in the same rotation
Chatgpt doesn't always see the correct way of fixing smt. Basing your work on that will turn out on loosing so much time on generating the same script over and over with new bugs piling up.
chatgpt is good at lookin for syntax mistakes and stuff (but ur IDE can do that)..
the only thing i think chatgpt is decent at is refactoring.. or helping u refactor
maybe i am just used to the tools i already got, but dont find it great for that either
i wish I could but idk how🙁
check the pins in this channel
ChatGPT is a text generator. Use it to generate text. It doesn't know code, so it doesn't really help with code. Sometimes people talk about code so it can sometimes accidentally say something useful, but only if that thing was said often enough that the LLM thinks that's what people talk like.
it was happening that with me, everytime i was doing the flip it was looking in the same direction and chatgpt didn't know what was causing it, than I realized it was because the y axis was set to 0 lol
https://gdl.space/anojikufet.cpp can anyone help me with this? my wave goes straight to 5 after the first wave and all the zombies spawn in the same place
Sorry, AFK. I saw someone use OnCollisionEnter and GetContact to use the Contact.point with WorldToCell to get the cell position
Once you have the cell position, you can get the tile with GetTile or use CellToWorld to get the tile position . . .
add a debug to see how many coroutines you are starting
I have an issue where when a DDOL object is initialised in the scene, and then i go back to that scene, a copy of that DDOL is made and i dont want 2 of them
how can i avoid this issue?
You're starting a coroutine every frame for 2 seconds before the first one actually spawns a wave. Then 2 seconds of coroutines all finish one after another because their waits are all done waiting.
Like that, assuming it returns a value
so should i reduce the coroutine time?
In start, check if another instance of this object exists already. If it does, self-terminate
You should wait to start the next coroutine until the next one is finished
ChatGPT documents my code/packages. It's great for writing summaries. Oh, and unit test. I use it as a first draft for unit testing . . .
how can i check for "other" instance? if i do findobject wont it just find itself
Usually by having a static reference to an instance of this object. If it's null, set that instance to itself. If it's not null, destroy self.
Your DDOL should be a singleton (pattern), which by default, checks if another instance already exists . . .
This is known as the Singleton pattern
i reduced it to zero but now it spawns to 3rd wave, should i make a variable for this?
how do i do this singleton thing? i think its finally time i just do it cus i keep hearing about it
What did you reduce to 0
It's relatively simple. You can find any tutorial online or on YouTube. Unity may even have one. Digi has a simple example to follow . . .
#💻┃code-beginner message
the time for the coroutine, the delay
So I'm trying to play sound however it does not appear to want to play... ideas?
public void changeImage()
{
Debug.Log("changeImage()" + "readInput.currentWord: " + readInput.currentWord);
if (readInput.currentWord == "manzana")
{
oldImage.sprite = apple;
audioSource.PlayOneShot(appleSpaClip);
}
AudioSource is assigned too
Volume appears to be set correctly
You want to prevent starting a coroutine until the previous one finishes. Right now nothing is stopping all of your coroutines from starting one after another.
should i implement the delay somewhere else? before i call the coroutine in the first place?
You should put in some method of checking if the coroutine has started before starting the new one, and then un-set that when the coroutine finishes
Show the inspector for this Credits object.
https://gdl.space/ejukurifew.cpp
idk if i've written this right, but i've followed a tutorial and made my gamemanager inherit from singleton and the issue still persisrs
The spawn variable updates now, but now a gameObject won't instantiate. https://pastecode.io/s/2hum7dzq
The function was not public
I made it public
Does the GameObject you dragged into the slot have the script attached to it?
yes
@open apex Also, make sure the method is public or it will not display . . .
Bumping this
is it because im not using the instance thing?
Inherit from Singleton? Did you create a Singleton class?
thats a singleton class yeah
Singleton is not a Unity class by default. You'd have to create one that has all the code. Did you copy/place code inside of that class?
i created a class, thats the link i sent
The spawn variable updates now, but now a gameObject won't instantiate. https://pastecode.io/s/2hum7dzq
Format your code. No one wants to read this. Mods warned you already a few times to format or stop posting
Ahh, I missed the link. Mobile scrolls fast . . .
How do I format?
what do i do with this singleton code? i created the class but not sure how to do it
Yeah . . . I can't read this, especially on mobile. Hit that format button . . .
when you want something to be a singleton you extned from it instead of MonoBehaviour
Depends on which IDE you are using. Google the IDE name and how to auto format the code
Your brackets are all messed up so it's really tough to see where a statement begins and ends
Thats waht i've done
This is the first part of the process. What did the rest of the tutorial say/do?
something about just referencing using an instance or whatever
thats it really
like gamemanager.instance or whatever
thats all there is too it
https://gdl.space/kibimapizi.cpp can anyone help me with this? i need to delay my coroutine so that it doesnt go straight to the 3rd wave/index. How would i do that
Any class you want to have DDOL will derive from it. No need to do anything else . . .
Yep, that's it . . .
so if i dont use the instance it just doesnt work?
what are you expectations
Maybe it's just because searching on mobile is ass but I don't see any instantiate happening in this code at all
I'm replying to this so I have an official final caution. If you post unformatted code again in the future, you will be muted. If you continue, you will be kicked.
You have been told over three times by now.
you simple access it with TypeName.Instance as a shortcut to let you reference that from anywhere now
Oh, hang on I see it, it was mobile searching
The instance will only be created when you access the instance property
(unless a component already exists in the scene, of course)
I'll let someone on a computer handle this
right
or you can just put it in a scene manually and it will find the existing instance
I explicitly access a few instance properties when my game starts up
void Initialize()
{
LoadData();
foreach (var mode in DefaultGameModes.Instance.gameModes)
mode.CreateConfig();
// make the menu load itself
var x = MainMenu.Instance;
gameSessionsStat.Increment();
State = GameState.MainMenu;
Application.quitting -= OnQuit;
Application.quitting += OnQuit;
DontDestroyOnLoad(gameObject);
}
so instead of creating like a field in the class, i just reference GameManager is a type?
I don't understand your question.
SomeSingleton.instance <-- after you evaluate this, the instance is guaranteed to exist
it creates a gameobject then adds the class to it
i see
(or are you talking about my code?)
read the code
well, what's your use case...?
i have this game manager object with multiple components on it
its simply a way to get a reference where ever you need it, and create it if it does not exist
If you need to instantiate an entire prefab, then you need a completely different singleton implementation.
😭
Read the dang code.
It does exactly what it says it does. No more, no less.
You can't just pray that it magically does what you intended
So, Instantiate runs in Start, if Spawn is false. If dropSet is 1, Spawn becomes true, otherwise it's untouched. So, either Spawn starts as true or dropSet is 1 when Start runs
okay im gonna look up prefab singleton then
there is a findobjectoftype it uses before creating it, so he could just manually create the instance in scene and use it for access only
now, fortunately, it's also really easy to make a singleton that instantiates a prefab
using UnityEngine;
public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
private static T _instance;
public static bool Safe => _instance != null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));
}
return _instance;
}
}
}
you can probably ignore the Safe property
So I'm trying to map two different words ("りんご” and "manzana") to the same currentJapWord and currentSpaWord... any thoughts on how to do that? Like how do I assign two different words with the same meaning to the same current word?
private void Awake()
{
foreach (Word word in allWords)
{
mappings[word.English] = word;
mappings[word.Spanish] = word;
mappings[word.Japanese] = word;
}
// Find the InputField dynamically during runtime
if (japInputField != null && spaInputField != null)
{
// Set the focus back to the input fields
japInputField.Select();
japInputField.ActivateInputField();
spaInputField.Select();
spaInputField.ActivateInputField();
// Set currentWord for both languages
//currentJapWord = GetRandomWord().Japanese;
//currentSpaWord = GetRandomWord().Spanish;
currentJapWord = "りんご";
currentSpaWord = "manzana";
I use that to test if an instance currently exists. It's relevant when the game is shutting down
i don't want to instantiate things while the game is shutting down
ah but i need to use resources, how do i use resources?
do i need to explicitly mark a folder as a resources folder or
also dont over use resources, everything you put in the folder gets included in your game even if never used
any folder named Resources
im probably only gonna use it for like 3 things so no problem there
yeah, you would not want to throw a huge pile of models into Resources
Read the link I just sent.
how would i do that? i have boolean that should stop it but it doesnt
does your prefab code account for if two of the same type exist?
I only ever create instances of these types by accessing the instance method, so that's impossible
I do not have a MainMenu prefab in any scene in my game
that was the entire motivation for this SingletonPrefab class - I didn't want to have a menu prefab in every scene, and I didn't want to have to worry about making sure I always started the game from a scene with a menu prefab that'd get DDOL'd or something
When the game starts, the prefabs are instantiated
oh right
it works really nicely
the GameController is responsible for making everything else happen
nothing else "starts itself"
i already have a gameManager prefab open in the scene, that could be t he problem ig
i see, the game manager isnt getting reinstantiated when i reference it again from the first time
I don't understand.
Find out which of those cases is preventing your instantiate from happening
Ok
https://gdl.space/wugohoguge.cs
hello im having a small issue
i have a
float currentHighScore
float reactiontime
if (reactionTime < currentHighScore)
o want the highScore to update
when you first play the game currentHighScore = 0f;
but reactionTime can never be < currentHighScore
i would be wierd if i set it currentHighScore to 100f; couse then the highscore wil be 100 at the start
is there an other way than this aprouch?
ur first reaction wouldn't compare to the highscore,
it would just log the reactionTime as the new highscore, then ud compare
Show code
You set is spawning to true after the wait
Meaning it won't block the coroutine from starting until it's already done
oh
You want to set your book before the timer and then un set it after
yeah
i got it it works now
@polar acorn thanks a lot! man idk how i missed that thanks a bunch
works i add a bool isfirstAttempt and did this
if (isFirstAttempt || reactionTime < currentHighScore)
isFirstAttempt = false;
and i also check if there is a score saved from last sesion then isFirstAttempt also be false
I can't find the case that's preventing the instantiate from happening.
What have you tried
I tried removing dropset++ and Spawn = True, but I kept getting the problem.
How about instead you just log those values in start and see what they are
Logging isn't a fix, it's to help you understand the issue.
If it didn't print anything then this code isn't running
Oh, I just moved dropset++ to another place in start.
So if you didn't do what I asked you to do why did you say that you did but it didn't work
I didn't know what you meant.
If you don't know what debug log is you need to stop everything and do the beginner tutorials linked in the pins.
sounds good!
Debug log should literally have been the first line of code you ever wrote
I'm trying to make a twin-stick shooter where the player follows the cursor, but when they sprint I don't want them to look at the cursor, and instead at the direction of travel. This is the code I have, but it's not working, even while running the character continues to look at the cursor. Any idea why?
void RotatePlayer()
{
if (isRunning == false)
{
transform.LookAt(new Vector3(cursorToWorldPoint.x, transform.position.y, cursorToWorldPoint.z));
}
else if (isRunning == true)
{
transform.LookAt(new Vector3(xForce, transform.position.y, zForce));
}
}```
this is being called in update
It's actually only facing the x value of the cursor, as soon as it passes where it sits on the screen, the model does a complete 180
Any ideas why I cannot tab into my next inputfield? I even have interactable set to true
think tab might want nav for moving down so could setup the rest of the references under navigation
use * not +
No dice
how do i draw this area with gizmos like with the offset
Physics2D.BoxCast(m_Coll.bounds.center, m_Coll.bounds.size, 0f, Vector2.down, .01f, jumpableGround);
isn't that times?
Quaternion is not a regular number, that is how you combine 2 rotations by applying one to the other with multply
Sorry wrong reply @shell sorrel lol
who also got rotate as a field, how are you setting it, quaterions are not what you think they are, the x y z and w components are not angles like you think
Odd, even the visualizer is showing that it should be able to tab between thw two, am I missing something in code?
I thought of Vector3 and I thought there would be something similar for rotations 😔
this was the best way i seen quaternions explained
there are methods you can use instead
i am trying to call an OpenAI API like:
-d '{
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What’s in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
}
]
}
],
}'
here's my 8 hour progress:
https://pastebin.com/Fs8MpWwu (just the relevant parts)
here's my error:
HTTP/1.1 400 Bad Request
line 58 on PasteBin.
don't bother explaining, i know i'm not sending the parameters correctly, but that's the issue...
i've done this before:
`"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
}
]
}```
**
but not:**
```py
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What’s in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "blahblhah"
}```
i switched the channel because i think a "general" programmer would of known how to fix it by now...
V3 is opposite , you add those together or multiply by a float
or AngleAxis or many others you can see for certain purposes
you can find them all as static methods on Quaternion
A * B is (A Rotates B) where B is the original oreientation and A is the rotation thats happening to it
I didn't know there was a w
this was helpful to me when i read it
like i said a quaternion is not what you think it is, so you are best to use the methods on it, and not directly working with its data
ya, only those still plugged into the matrix can visualize quaternions
https://quaternions.online/ heres a fun interactable
yeah many methods to work around it though like AngleAxis, LookRotation etc
most of what i do is do some vector math to get a direction then LookRotation that
if (Input.GetMouseButton(1))
{
rotateCurrentPos = Input.mousePosition;
Vector3 difference = rotateStartPos - rotateCurrentPos;
rotateStartPos = rotateCurrentPos;
newRotation *= Quaternion.Euler(Vector3.up * (-difference.x / dragRotationSpeed));
}```
ya, i pretty much use` Quaternion.Euler `like its going outta style
I am just trying to rotate z to a 180 😔
@silver sun Do not crosspost. #archived-code-general
transform.rotation = Quaterion.AngleAxis(180, Vector3.forward)
I did the * you told me,
But it does 180 times 0 which make it still 0
ahh, i havent used the .AngleAxis just yet
The problem is, I don't know why. I don't understand what I am reading sometimes
make it *= if you want to rotate 180 from where it is already
i know the rule, i read them, did you want me to delete the old one? because only after i realised that it's not a beginner channel.
if you've commited a crosspost.. then yes, probably delete 1 of em
It was already removed, and you reposted it in #💻┃code-beginner. So knowing the rules is questionable.
Just pick one channel and stick with it. It's up to you if it's beginner or general.
hey so i could use some help with something so basically my player is colliding with the ground fine as you can see with the image thats my code for the boxcast and for some reason it will randomly say it isnt colliding with it and wont let me jump any idea what im doing wrong here
public bool IsGrounded()
{
return Physics2D.BoxCast(m_Coll.bounds.center, m_Coll.bounds.size, 0f, Vector2.down, .01f, jumpableGround);
}
because it was pretty far up anyway... what a thing to compare about "breaking the rules"..
i was just answering what i'd do.. u asked
when i mean randomly i mean i have a hard time reproducing it it takes like 5 minutes to reproduce it
hmm, is it a certain area of the level?
okay, noted. but my bad i intended to reply to Osteel
or just generally anywhere
so it seems to trigger around a certain point in the level and then no matter where i go it doesnt fix but it also triggers other spots its just one spot normally is the main spot it occurs
i beilive its something to do with that part but im also not entirly sure
the 0.1f in ur boxcast may be too small for all scenarios (on flat ground yea,, but maybe in other situations its not big enough?)
yes but when im back on flat ground that should be fixed no?
like i cant jump anywhere after this happens
other than that its ur basic groundcheck 101:
- is the playerobject and ground set up with the correct layers
- is the layermask including these layers
- check the size and position of the boxcast
- check the distance
- etc
like i cant jump anywhere after this happens
thats an important tidbit of information ☝️
sounds more like maybe an error.. if u get a null error or somthing in the code, that code will just stop working
do u have any errors in teh console when it happens?
nope no errors or even warnings
do u call the bool in the code? (like in all the right places?)
maybe the code bypasses it for some reason
i tried in update setting a public variable to it so i could see and after the glitch happens its just always false
but im talkin about teh bool .. unless u use the bool, (the physics boxcast wont run) and then ur groundcheck will never be true anymore.. unless its called. maybe the code for that bit is broken
best to send the code anyway, in a pastebin site or something so we have some context
these types of errors usually aren't just the singular ground check thats wrong, its usually a multi-piece problem
here is the whole script
https://pastebin.com/Cg5Unzbg
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.
im gonna go ahead and guess it has something to do with u having 2 bools for grounded. and trying to manage both of them.. as well as the coroutine that has to wait half a second to set m_Grounded back to false
im still looking thru it.. not seeing it right off the bat.
wdym 2 bools for grounded m_grounded2 was just so i could visualise what it is at all moments
it was happening before i added that
and the half second wait was because before it would instantly set it to false letting you double jump because you technically where still touching the ground
i think its ur .1f like i said originally..
heres my test using the bool raycast return like you have with a .1f (never gets grounded b/c the player is too thicc)
and heres my test using the bool raycast return like you have with a .75f (works as intended)
yeah so that seems to fix it
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
}
private void Update()
{
isGrounded = IsGrounded(); // updating every frame (so we dont miss any ground detections)
float horizontalInput = Input.GetAxis("Horizontal");
Vector2 move = new Vector2(horizontalInput,0f);
rb.velocity = new Vector2(move.x * speed,rb.velocity.y);
if(isGrounded && Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
private bool IsGrounded()
{
float raycastLength = 0.75f;
RaycastHit2D hit = Physics2D.Raycast(coll.bounds.center,Vector2.down,raycastLength,groundLayer);
TestGround = hit.collider != null;
return TestGround; //used a TestGround boolean that I exposed in the editor
}
private void Jump()
{
rb.velocity = new Vector2(rb.velocity.x,jumpForce);
}``` just used your code and stripped out all the animations and extra noise so i could focus on the groundcheck
ya, that was my first guess and gut reaction, and thats what it ended up being on my end
i also just realised the gizmos is 0.1 and the actual boxcast is 0.01
so it may not have been colliding lol thanks for the help
yea .01 is extra tiny
yeah didnt think about that i thought it was .1 lol
another thing is, learn about Gizmo's
u can draw them using code.. and it'll really help out trying to visualize these things..
private void OnDrawGizmos()
{
// Draw a raycast line to visualize ground detection
Gizmos.color = Color.green;
float raycastLength = 0.75f;
Vector2 raycastOrigin = coll.bounds.center;
Vector2 raycastDirection = Vector2.down;
Gizmos.DrawLine(raycastOrigin,raycastOrigin + raycastDirection * raycastLength);
}``` ^ that example
yeah i was drawing them already lol
oh okay 👍 just trying to give ya some things to help
sounds like ur pretty good tho
yeah thanks any way
np, 🍀
Would recommend OnDrawGizmosSelected() in case I want to only see the gizmo on the object(s) selected in hierarchy.
true true
Did you read the paragraph that tells you what that error means?
Great, so you have some gradle errors. Ask about them in #📱┃mobile
You're trying to build but have some UnityEditor classes that you cannot export
put scripts in editor folder or wrap in #if editor
^ MenuScript is gonna have to be modified
public bool DetectChanges<T>(T firstValue, T secondValue)
{
return (firstValue.Equals(secondValue));
}
can i get a vibe check on this, would this work as intended for objects like monobehaviours, so's etc.?
How is it different from doing an Equals directly?🤔
Oh it's a validation thing i'm gonna have some optional debug logging in here in theory
Okay. I don't really get the question then. It would work the same as if you're doing an Equals directly.
whats this do? im curious
This is identical to just doing ==
Sorry, new to generics and wasn't sure if me passing in stuff like monobehaviour, scriptableobject etc. generically would make it fail an object comparison like this
ahh, Type == Type?
nah i want object instance
Object == Object ? im just curious what its for
Syntactically, this is all sound, but functionally, it's the same as ==
Equals can be overriden though, so the behavior might vary depending on the object.
For full context i'm developing a custom content api mod for Lethal Company and I want to detect and log user changes to values in the custom content via config files
If you want to detect changes you're going to need some sort of previous value to compare it to
ooo.. and if u modify something in one object the comparison is supposed to fail??
thats what i'm doing, no?
This is checking if two objects are equal, the hard part is actually getting the previous value
Reference types check reference equality. So even if the contents are the same, 2 objects would never be equal
as far as i know ur just comparing two objects, if its the same object
didnt expect this
the two object are the previous and new value
oh?
b/c its different *entities? (identifier, GUID?
For reference types, == and .Equals check if they're literally the same instance
Unless you(or unity) override their Equals method
Also, if they are the same instance, if you change a variable on one of them, that variable would be changed on both variables pointing to that same instance
If I have a cat, and I tell you about my cat, and then I put an adorable little bowtie on him, the cat that we're both thinking of now has a bowtie
ya, okay yea thats what i thought i read. lol
To put it simply, your method doesn't really detect any changes.
Unless you're planning to use it for value type mainly.
The name of the function might be a little misleading,
I don't want to detect if something has changed. I want to check if setting x to y would be changing it
Well, then no. It would always return false if x and y are different instances.
Even if it doesn't change anything.
yeee but if x and y are the same instance it'll like detect that correctly right
i doubt it
i mean if ur asking if its the same instance with different data /values
If X and Y are the same instance then they're the same instance and changing anything wouldn't matter
what your saying here is exactly what i want to log
which is the purpose of this function
If they are the same inatance, then yes, that would work. But what's the point of the check then?
ya, if its the same instance how is anything supposed to be different?
what is the actual purpose of the function?
I'm not sure what you mean. If they're the same instance then they're the same instance, how are you going to detect if one of them has changed
one moment
eg. i want to use it like
public void DebugDetectChanges<T>(List<T> firstList, List<T> secondList)
{
string debugString = "Detecting Changes" + "\n";
if (firstList.Count != secondList.Count)
debugString += "List Count's Differ, Changes Confirmed!";
if (firstList.Count >= secondList.Count)
{
foreach (T item in firstList)
{
debugString += "Detection Check #" + firstList.IndexOf(item) + " - (" + DetectChange(item, secondList.IndexOf(item)) + ")" + "\n";
}
}
}
public bool DetectChange<T>(T firstValue, T secondValue)
{
return (!firstValue.Equals(secondValue));
}
It seems you need to check if the value of a field on an instance is different than the new supplied value . . .
If the user have created a new instance of a type and tries to assign it somewhere. Is that what you want to check?
Okay, in that case, == works fine
its mad at me
You need a constraint for T . . .
( might be misusing generics, i'm new to them)
What does the line of code look like?
return (!(firstValue == secondValue));
generics confuse me. so its an extra layer of complicated when i watch them get debugged by others lol
You're comparing the types, not a value of the type . . .
ah
That's not true though
ya, thats why i originally asked at the begining, do u mean Type==Type
ohh.. nvm lol
I think you just need a constraint how random pointer initially.
The problem is a lack of constraints
I have two lists of values and i want to have a easy way to check if there are differences in the two lists
the two lists will always be the same type but i want to do this check with multiple types if you know what i mean
If one is a reference type and the other is a value type, a null assignment will be an issue . . .
They need a type as a common denominator . . .
They are the same type, both T
You won't be able to use ==, but you can use Equals, and should add IEquatable<T> as the constraint
IEquatable will use its—the type—default Equals method. So it disregards the type mismatch, doesn't it?
DetectChange(item, secondList.IndexOf(item)) this is nonsense however
Howso?
it should also not compile
hey
howdy
There may be differences if the two lists count are the same (assume they are not same instance)
can you jump in my call with me and my buddy please
no, that is not something i do, but we can text here
ok thats fine
We'll move into here because it is a bit more of a code thing anyway. Send a screenshot of the object that has your script on it
so when i start a new project and then i add canvas then add script through canvas on add component then typ to say hello
So show a screenshot of your canvas with the script on it
i got it sorry for the inconvience guys i didnt know you had to drag the script over and attach it to canvas or main camera
Coding is an ass that is full of farts.
That is usually where the farts come from
Coding is a class that's full of art
I started watching an instructional video at 11am today and have been stuck trying to get this message to appear until this very moment
I have read 6 miles of forums and had no one help me change a setting that properly linked unity to VisualStudio
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
We literally have a bot command explaining how to do that
I have learned this now. Thanks
Paste of code isn't working, any alternatives?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
To be honest I kinda got lost in the tutorials but here
https://hastebin.com/share/azusepehic.csharp
Basically the terrains are creating fine but I am not seeing shit in the game view I only see them in the inspector. And once I move past the observable distance, it does actually hide the ones outside said distance. After looking at it for a while, I noticed the mesh filter is not getting applied and stays empty which is weird because I do in fact do that in the UpdateTerrainChunk right after checking for if the mesh data has been gotten. Pls tell me if u want to see other parts of my code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey, just wanted to remind you about the learning portal. It is wise to take the Junior Programmers Pathway. at least, the first couple sections
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how can i change my textmeshpro outline colour through script?
wait I sent explanation of what happened and a link to hastebin but I think it got blocked
Yh I can't reply it
your message and link came through fine to me
I have a scriptableObject. And every Time i call it it has to be initialized. Whats the point of ScriptableObjects if they have to be built everytime i call them?
They don't. What exactly are you doing? Share code.
{
//print("Looting something "+index);
ItemDatabase itemDatabase = ScriptableObject.CreateInstance<ItemDatabase>();
Item newItem = itemDatabase.GetItem(index);
print("Index: "+index);
print("NewItem: "+newItem.Name);
foundItem = items.Find(item => item.Name == newItem.Name);```
and unless i put Awake{initinializeItems();} inside itemDatabase, i cant access any of the items.
Doesn't seem like a correct way to use SOs.
The whole point of SOs is that you can reference an instance of it as an asset.
Here you're just creating a new instance every time.
but when i public ItemDatabase itemdatabase; unity yells at me and says instance of object is not found.
damn it unity
Do you actually assign it in the inspector?
scriptableObjects cant be assigned in the inspector, it has to be a monobehaviour
assigning it in the inspector is like the first thing you see online when learning SO
Ofc they can. That's the whole point of them😅
well then i am missing something, because i cant assign a script unless it is a component
You are mixing things up. You cant put a SO on a gameobject you can put it in the field of a component that is already on a gameObject
i am not allowed to put any scripts into a field unless it is attached to a gameObject.