#๐ปโcode-beginner
1 messages ยท Page 286 of 1
What happens if it doesn't/isn't-able-to find the object?
i fixed the issue, i'm just stupid. but i don't know why it refused to get the object since the objects were in the scene and had the correct names ๐ค ah well, if it ain't broken, don't fix it
Because the first one is valid C# syntax. The second is not.
Because -5 < y < 5 isn't a thing
how?
How what?
that is a thing...
not in boolean logic it isn't
if takes a boolean as a parameter. < is an operator that returns a boolean when given two numbers. x < y < z would evaulate to (x < y) < z) which would be checking if false was less than z which makes no sense
because what you have is basically this:
((-5 < y) < 5)
that then get's evaled this this:
(true < 5)
and that doesn't make sense
yeah that makes sense
understood understood
ty
beat me to it ๐
https://gdl.space/femerohidi.cpp in my code in line 57 the for loop refuses to execute even though both conditionals in the AND gate are true
Do you get your log "hit"?
yes
So, just to make sure, you want to run this loop over Classes.Ship.list[i].Object_List until you find any element whose type is not "Glue", then exit, right?
no Type must equal "Glue
Right, so as soon as you encounter something whose type is not glue, exit the loop
right?
no just continue looping until the end
As soon as the condition is false it's going to end the loop
that's the entire point of the middle parameter of a for loop
oh
the loop runs until that statement returns false
If you want to loop over everything and do something if that thing's type is Glue, just use a foreach with an if statement in it
Thanks it works now, cant believe I was stuck on it for 2 days I knew it will be something stupid
Why does
private Vector3 GetMousePosition => MainCamera.ScreenToWorldPoint(Input.mousePosition);
Give different position every other frame?
Origin: (-319.10, -31.11, -10.00) Difference: (-259.77, -7.96, 0.00) MousePos: (-578.87, -39.07, -10.00)
Origin: (-319.10, -31.11, -10.00) Difference: (0.00, 0.00, 0.00) MousePos: (-319.10, -31.11, -10.00)
Is your camera moving
If the camera moves, the world position your mouse is at also changes
I am trying to use input system Vector as a mouse position to see if that helps.
oh
I've been following an old tutorial
Maybe its outdated?
or perhaps I have to setup my camera in a specific way
Try logging Input.mousePosition and see if it's actually moving
its not
Origin: (28.22, 47.03, -10.00) Difference: (28.22, 47.03, 0.00) MousePos: (56.44, 94.07, -10.00) MouseInputPos: (633.50, 378.00, 0.00)
Origin: (28.22, 47.03, -10.00) Difference: (0.00, 0.00, 0.00) MousePos: (28.22, 47.03, -10.00) MouseInputPos: (633.50, 378.00, 0.00)
Hmm, its still flickering.
MainCamera.ScreenToWorldPoint( this part is causing the issue, I probably need to deduct the starting position, or update starting position on each frame as I move the camera.
Maybe show your logging code
Looks like there isn't any problems with the property
public void OnDrag(InputAction.CallbackContext ctx)
{
if (ctx.started) DragOrigin = GetMousePosition;
IsDragging = ctx.started || ctx.performed;
}
private void LateUpdate()
{
if (!IsDragging) return;
DragDifference = GetMousePosition - DragOrigin;
Debug.Log($"Origin: {DragOrigin} Difference: {DragDifference} MousePos: {GetMousePosition} MouseInputPos: {Input.mousePosition}");
transform.position = DragOrigin - DragDifference;
}
private Vector3 GetMousePosition => MainCamera.ScreenToWorldPoint(Input.mousePosition);
What's the issue? It looks correct where your mouse in world coordinates is changing because your camera is moving.
If you want it not relative to the camera position, subtract the camera position from the result and you'll get the position without the camera offset.
I am just not sure why it works in year old tutorial, but not for me.
Describe what you mean by work and not work?
In the tutorial it drags the camera without flickering
If you're referring to the coordinate changing because your camera is moving, it's got nothing to do with versions
in my case it changes position every second frame
Yeah, but the code in the tutorial works, but doesnt for me.
Even tho I did everything the same(I think codewise at least), so what could be different?
Trying to mess with z index of the mouse output based on some comments under that video.
I know its not the solution, but just want to see whats wrong <_<
What do you mean by "without flickering"?
Sounds like the ui isn't updating quickly enough or possibly desynchronized movement (physics step vs update)
Origin: (746.02, 203.33, -10.00) Difference: (54.99, -40.52, 0.00) MousePos: (801.01, 162.81, -10.00) MouseInputPos: (527.50, 402.00, 0.00)
Origin: (746.02, 203.33, -10.00) Difference: (-177.28, 123.73, 0.00) MousePos: (568.74, 327.06, -10.00) MouseInputPos: (529.50, 403.00, 0.00)
You can see MousePos changing by a large amount every 2nd frame, I am using LateUpdate as in the tutorial.
I just dont know why it works for the guy in the video, but not me ๐
It is teleporting randomly. Not sure what you're seeing
I don't know what you mean by not working so I can't help you.
mousePos x: 801 then 568 next frame.
public void OnDrag(InputAction.CallbackContext ctx)
{
if (ctx.started) DragOrigin = GetMousePosition();
IsDragging = ctx.started || ctx.performed;
}
new input system -> Button -> Right mouse button
could probably lerp it as a bandaid
I will find/figure out a better solution, I am just trying to figure out why the video tutorial works, but not when I try it on my side
I must be doing something wrong, or my unity version is different from that video <_<
ya sure it's not local to what you're dragging
I attached this script to camera
if (ctx.started) DragOrigin = GetMousePosition;
This doesn't cache if that matters since you're always getting a new point each time it's accessed
Maybe instead of converting into world coordinates just add the difference? position -= delta
I think ctx.started happens only once on mouse down?
It seems to be the case if I hold mouse and drag far the "difference" gets higher
oh, right it only should do it once
As your camera is moving in the world, you'll get teleporting
LateUpdate is interesting but most dragging ive done is through IPointerDrag
Hello, is anyone willign to explain the axis controls for rotating character joints in better depth to me or link me to an explanation. It seems confusing and like it sometimes defys being a direction or rotation (im guessing it is due to it being local to the object transform)
This solution from that video comments almost fixed the issue:
private Vector3 GetMousePosition()
{
Vector3 MousePos = Input.mousePosition;
MousePos.z = 10;
return MainCamera.ScreenToWorldPoint(MousePos);
}
Since my camera is at z -10
Things to consider Move Mouse Update Camera Position (The mouse is no longer at the assumed world location as the camera has moved) etc
{
if(collision.GetComponent<BoxCollider2D>())
{
BoxCollider2D boxColliderCollision = collision.GetComponent<BoxCollider2D>();
if(boxCollider.size.x > boxColliderCollision.size.x && boxCollider.size.y > boxColliderCollision.size.y)
{
_resetOnDrop = true;
}
}/**/
}```
Is there a reason that this if statement is not working?
define not working
put debug.log first before if statement to see if its even running
If you just offset the camera position by mouse position in screen space, it'll not change bizarrely
Ill do that also
also collision..GetComponent is prob wrong, you prob just want collision.collider
_resetOnDrop is not flipped
One message removed from a suspended account.
!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
make sure you code editor is showing you these syntax errors
time to start debug logging those values then
Do I need to use it with canvas/UI? How do you detect when something is being dragged?
I think that I should be able to do it with just detecting mouse pos and moving camera based on that value.(difference between origin + camera pos)
IPointerDrag can be used on anything, but your issue is more related to the camera anyway
if camera is at 0,0,0 and mouse origin at 20, 20, 0 then I move mouse to 30, 20, 0. It should move camera to 10, 0,0
I think thats the logic.
Further simplification after your issue is fixed, to check whether the collider you hit is a box collider, prefer the is operator:
if (collision is BoxCollider2D col2d)
{
// use 'col2d' variable to directly access the collider as a BoxCollider2D
}
thanks so much
this would be error no?
collision is a custom clas
hello im having a nullreferenceException problem and i dont know exacly how to solve it
half the time I use the documentation and am told it is wrong tbh
I don't see why you can't do this using the late update and new input system. You'd just move your camera relative to the mouse delta in screen space.
it's only wrong half the time
Yep that parameter really should be named collider lol, I thought that you were using CollisionEnter for a second
lol yea , no wonder collider.GetComponent wasn't throwing error for them
I'd need more details on that, but I will try.
I was just adamant on figuring out why it works in the video, but not for me ;_;
Could be unbound on the editor those references, but consider debug logging if they are being instantiated somewhere in the script.
also if you are doing multiple dot access operations, then debug left to right.
Without all the fancy stuff it's practically just cs transform.position -= dragDifferenceInScreenSpace;
Use a scalar if you're wanting to decrease or accelerate the camera movement.
private Vector3 GetMousePosition => MainCamera.ScreenToWorldPoint(Input.mousePosition);
No because when you move your camera, you're moving your mouse position in world space.
Ah I really need to learn about screen/view/world positions -_-
I get the idea, but not enough to understand what I am doing lol
Learn OpenGL . com provides good and clear modern 3.3+ OpenGL tutorials with clear examples. A great resource to learn modern OpenGL aimed at beginners.
OpenGL but similar concepts
Thanks
Is there any way to increase the time we spend on loading screen? Right now it happens in an instant and I cannot even read what it says on the screen. Also cannot event properly see my progress bar doing its job.
oh so just ising Input.mousePosition already made a huge difference.
The dragging is wrong, but its not flickering anymore
are you using a coroutine ?
Well its actually very wrong if I move away from 0,0,0
Yeah
I was told twenty years ago when I was working on a loading screen that people don't like loading screens.
You could put some artificial delays in between
My friends will complain if I dont show them what it does ๐
So I wait for seconds?
pretty much
Some games I know add "press any key to continue" for their loading screens
yeah that too ^
Like I was wondering if i could like see the progress bar going.
cyberpunk to
How are you doing the loading screen in the first place?
Loading a seperate scene which is purely for loading screen. Then I additively load another scene while on the loadscreen. Progress bar increases while the last scene I want to be in is loading.
I do the loading stuff in coroutines
It would be instant if the task isn't something your modern hardware will struggle on.
Its literally just an empty scene with ui elements T_T
Should be pretty trivial to implement since you're already using coroutines here
I guess as you said, I can just do an artificial wait then
I was not expecting the loading and transitioning between scenes to be this hard
Is it better to have a lot of scenes or as few scenes as possible? Also, how would you manage scenes in an optimized way? This will become messy with more than 10 scenes, no?:
If you do async loading https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html can show your progress using the progress value from async operation https://docs.unity3d.com/ScriptReference/AsyncOperation.html.
It'll still be instant though if the task isn't extensive.
Oh also. I need to keep some of the manager stuff persistent regardless of the scene. Should I make a seperate scene and like keep it loaded all the time? I
Yeah I do async loading. It still is in an instant but like I keep it at loadingscreen for about 2 seconds now and it should be enough.
Are loading and changing a scene two different steps?
public void OnDrag(InputAction.CallbackContext ctx)
{
if (ctx.started) DragOrigin = Input.mousePosition;
IsDragging = ctx.started || ctx.performed;
}
private void Update()
{
if (!IsDragging) return;
DragDifference = DragOrigin - Input.mousePosition;
transform.Translate(DragDifference * Time.deltaTime * DragSpeed);
DragOrigin = Input.mousePosition;
}
Going back to my problem.
This "works", I just need to set DragSpeed to 200 for it to be usable, but it works well.
Actually removing Time.deltaTime works perfect at 1 drag speed.
isn't moving in Update bad and should be done in fixed update?
Yeah like you can load a scene you want while still being on a different scene
You wouldn't want delta time for determining the mouse position either way 
for rigidboies yes. they're using translatinon though. Same as "teleporting"
Oh I see, should really look into to while im jamming this game jam
I mean if any movement isn't multiplied by Time.deltaTime, then it just happens a lot if you run on 144 fps, but only a few times when running on 30 fps
Correct me if I'm wrong
private void Start()
{
//isGameActive = true;
}
private void Update()
{
// Check for the Escape key press
if (Input.GetKeyDown(KeyCode.Escape))
{
PauseMenu();
}
}
public void MainMenu()
{
SceneManager.LoadScene(0);
}
public void Play()
{
SceneManager.LoadScene(1);
}
public void Resume()
{
pauseMenu.SetActive(false);
}
public void PauseMenu()
{
pauseMenu.SetActive(true);
}
public void Quit()
{
Application.Quit();
}```
Anybody have any idea why my buttons in my canvas are unclickable? The same UI in my main menu scene works but not here?
any value that needs to increase/decrease steady regardless of fps yes needs *time.deltaTime.
Rigidbodies are exclusion to the rule they already do their own calc
background is prob ontop of the buttons
the order should always be, background elements go top of hierarchy for UI (last = drawn above)
or on Image component disable the Raycast Target
thanks lemme try this quick
Everything is fixed, learned much, do not what I would do without this discord ๐ซก
I almost threw a tantrum when my sliders had weird hitboxes once. Turns out canvas objects fuc with that stuff. Playing around with it in another scene for like an hour made a lot clear
which one is the background image?
your event system is disabled..
thats probably why
ffs its always the most stupid things i waste 5 hours on
tru
Had error code telling me envent system runs with old input system, when I only used the new ne
you mean the legacy system?
Yea
Input module
Input.GetKey
yh i think both require eventsystem
Input Modules requires upgrade when using new Input System
I see, is that built in or do I have to change it myself?
regardless event system is needed for canvas raycaster
you get a prompt usually in the inspector for event system / input module
Wait a sec Ill show u
is it normal that when i press a button, unity does detect it but sometimes does what it's supposed to do and sometimes not?
probably not?
we don't know what "normal" is without context
I think you may have the problem I had, try only using one UI element first to check if that is working fine
is it frequent?
Had multiplie UI Elements bugging my sliders or buttons
except this is not happeneing with ui
what is the actual issue in the code?
Ah so this is that
yes the message is pretty clear
you have code using one input system while having player settings to another setting
idk, what i have is a bunch of values compared to check which animation to play, but the character having the same position, on some runs plays the animation and on some others it doesn't
You cannot use Input class if you have new input system selected in player settings
unless you had Both on (not ideal)
Is there a way to get camera x,y position to stay consistent even after changing camera ortographic size?
There is no InputSystemUIInputModule tho
this Input class has 0 to do with UI
You can reference the transform component of the camera
private void Update()
{
if (!IsDragging) return;
DragDifference = DragOrigin - Input.mousePosition;
transform.Translate(DragDifference * DragSpeed);
DragOrigin = Input.mousePosition;
if (transform.position.x < 0) transform.position = new Vector3(0, transform.position.y, transform.position.z);
if (transform.position.x > 2200) transform.position = new Vector3(2200, transform.position.y, transform.position.z);
if (transform.position.y < 0) transform.position = new Vector3(transform.position.x, 0, transform.position.z);
if (transform.position.y > 3000) transform.position = new Vector3(transform.position.x, 3000, transform.position.z);
MainCamera.orthographicSize += 1;
}
I am trying to lock the camera within certain bounds, so when I drag it, you cant go beyond those points(hardcoded for now)
But when you change its size, camera x,y wont match my previous setup.
Camera 0,0 is no longer bottom left corner of my worldmap, the corner becomes like 250,300 after resizing camera bit.
So if I force the corner to 0,0 the camera will leave the worldmap bounds.
here's the code, tho it might not make sense since it's made by me, but i used the two debug's first to figure out the right values to compare the differences to, which are the differences on the x and y axis between two gameObjects
whats with these very specific numbers
they don't have much meaning, try using variables
here's how i calculated the differences
Is this on a canvas? you could try to make it scale with screen (camera) size
Thats for me?
i used them to see where the player is compared to a tree
No for organic
The negative 3.5 is unnecessary in the first one. Same with negative 2 in the second, negative 1, etc
This is for you
what for ? sounds like overcomplicated way to animate something
I have an issue with the mouse position being captured incorrectly when I load the scene which requires the mouse position to be captured. but when testing the scene in isolation, the mouse pos capturing feature works properly. This is probably because my camera position changes between the two scenes, but as the scene's camera is used for taking the position (not the previous scene's cameras), I don't know why it doesnt work
wait, i just had an idea, what if i could make a 3x3 grid around the tree, and for every cel the player is in, a different animation is played
yeah i agree
i should be payed for this
I already reference it I think, in my code above, but camera x,y change when you resize it(if I try to keep my camera stuck to the bottom left corner of my world map)
Is there a way to work with that?
Maybe I need to update camera position.
I think camera pivot might help, so when its resized its stuck to the bottom left.(not sure if thats the way tho, but its a start)
The camera shouldn't move when changing that
i did remove them before but didn't work the right way ig
is this possible tho?
You could make it static then
SCENE CHANGE AND CAMERA CHANGE -> MOUSE POSITION NO LONGER BEING CAPTURED CORRECTLY
Ah I think I know what you mean
Correct, its not moving. But its bounds are changing(due to changing the size) so I have to reposition camera so its edges are in the same position.
My goal is to add zoom in/out to the camera, but also keep bounds.
Check how much the camera should be moved when changing the size by 1 and add that to the x and y
So camera cant go outside of 0,0(bottom left), but after resizing the camera ortographic size, 0,0 is no longer the same from camera point of view(because its origin/pivot is in the center?)
Let me try that, I was hoping for a more automated way, but its a good start ๐
540.2 size is "perfect" size that match my worldspace canvas at 0,0
Then have a script do something like
int size = (int)[GetSize]; (you need to implement GetSize)
float x = someValues * size;
float y = someOtherValues * size;
this.transform.Translate(new Vector2(x,y));
yes this will get complicated, I cant calculate the size properly, even manually <_<
Can I/should I add collider to camera?
Only if you want it to get stuck
I can use that to detect if camera left map bounds
Can't think of a better automated way this quick: I'm kinda jamming rn so sorry for not being able to help you further
Tbh I am surprised that there areny many guides on camera drag, I remember looking for it in the past and its the same stuff.
No one needs camera drag in their games? ๐ฎ
You could try some cinemachine tricks
I forgot to install the input system package....
You would think it'd automatically install while restarting the editor tbh
why people always uses vector3 while creating character rotation? if it is 2d platformer for example
why we cant use vector2? why we need z
neighter make sense for for rotation
To turn it sideways?
sure
Like tripping
Well for starters in 2d you are rotating around the z axis
Yep
but isnt z a depth
Z axis is actually the best as you won't ever lose sight of your 2D characters regardless of the z rotation
you only use a float if you use rigidbody which is prob how you should move/rot character
no v3 needed
thats only true in the unity default 2D setup
If you rotate around x or y you can't see them near -90 and 90 degrees
okey next question
Yeah true
made plenty of faux 3d topdowns by using the Y axis as camera forward
so plane was Z,X
But you will always move on the 1 and 2 axis, while rotating around the 3 axis
rotating on Y
why we using vector 3 while turning character sideways? ```private void Turn()
{
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
IsFacingRight = !IsFacingRight;
}```
for example here
I would use flip sprite
just cause localscale is vector3 by default in unity?
same reason you can do
transform.rotation = Quaternion(0, 180, 0)
to rotate left
yes Unity is a 3D engine
V3 and V2 can be plugged in the same
i mean i just wanna know WHY we use vector3 in turning 2d
they just can't be in the same operations
only because scale is vector3 by default kk, ty
the default setup in 2D is the camera looks down the Z axis
so it only makes sense rotation happens in that axis
Well I don't know how thin a 2D character is, but if the Z axis is 0 it wouldn't be visual
but again since its 3D engine you can rotate on Y axis and still get a flip effect (side scroller flip)
unity renders sprite on mesh / quad iirc
2d also doesn't fundamentally change how the transforms and engine itself work. It's still a 3d world, you're just using 2d assets and a probably an orthographic camera
the only differences is 2D uses box2D for physics and 3d uses physix (so obviously you cannot mix match colliders / rbs)
but they pretty much have the same method thanks to unity's api
Don't they work the same just forgetting about the 3rd dimension?
still can't solve this :/
hence why Rigidbody2D has no Vector2 for rotation
there is only Float needed for rotating 2D
shouldnt it move character like this? or in 2d we can use it cause z cord doesnt matter?
this is mainly an #๐โanimation question it seems
idk what picture this is..
but just to clarify in UNITY Engine, you can rotate a 2D object in ANY 3 Axis (x,y,z)
but typically you are doing it on Z axis
because the default view is Looking in the Z+ direction
quaternions are kinda irrelevant here..
unity inspector uses Euler angles, and so should the methods you use . Unless its a rigidbody 2D which again you need Float
well :/
hello can someone help me figure out why these things wont show up? im trying to follow a tutorial and this isnt mentioned in the tutorial
!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
thank you very much
So after looking around a bit it seems like i dont have unity api to use its IntelliSense
i dont fully know why i dont have unity api since i installed from unity and my code even says its using the unity engine
What does that even mean
Configure it by following the steps in the above link for your individual IDE and it will work.
ill try to follow it again
but from my understanding intellisense is what this is and it requires unity api
idk if that made anymore sense ๐
Here's an alternate presentation of the steps with some extra troubleshooting https://unity.huh.how/ide-configuration if it helps
how do i paste code blocks?
''' public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Object prefabSource;
SerializedProperty prefabProperty;
prefabProperty = property.FindPropertyRelative("prefab");
EditorGUI.BeginChangeCheck();
{
prefabSource = null;
EditorGUI.BeginProperty(position, label, property);
// Draw the prefab field
EditorGUI.BeginDisabledGroup(true);
EditorGUI.ObjectField(position, label, prefabProperty.objectReferenceValue, typeof(Poolable), false);
EditorGUI.EndDisabledGroup();
if (GUILayout.Button("Store Prefab")) {
var targetObject = property.serializedObject.targetObject;
prefabSource = PrefabUtility.GetCorrespondingObjectFromOriginalSource(targetObject);
}
EditorGUI.EndProperty();
}
if (EditorGUI.EndChangeCheck()) {
Debug.Log($"set by hand");
Debug.Log($"auto set {prefabSource}");
prefabProperty.objectReferenceValue = prefabSource;
}
}'''
you've been here for years, why is this a question now? !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.
thank you ill look thre too
I know this may be a stupid question but are you definitely using the MonoBehaviour class type & not a standard C# class?
im new to coding so i dont fully understand what that means ๐ญ
but the code does say monobehavior
Can you share your entire VS Code Window?
sure where is that
That looks like VS, not VS Code, but I might be mistaken
like this? its on visual studio 2019 btw
Show your External Tools settings that that you have the Unity workload installed in VS's installer
https://hatebin.com/wziljhqdll looking for a small fix, in my code I have different movespeeds for 4 states, in the air, sprinting, walking, and crouching. Everything is working fine, except my player is not switching to the crouch speed that is set when I hit the crouch key. The crouch happens still, but the state doesnt switch to crouching in the inspector.
is this what you mean
No. You would know what it was if you followed the instructions
it doesnt say vs anywhere but i just searched external tools in visual studio and foudn it
It seems to me, like you don't stay in that state for very long. I'd debug log each state transition to understand what's happening.
https://youtu.be/vi-4GyO95d8?si=5vDoUf-BJsMLJWRl maybe give this a try?
hopefully this helps all you getting into scripting
im just blind i guess ๐ญ
ok ill give it a whirl
THANK YOU THIS WORKED
thank you both for your help ๐
and sorry vertx i guess i missed some stuff ๐ญ
i assumed that since i already installed visual studio through unity i could skip that first section and went to whatever looked like my problem
Next time don't just randomly skip instructions
i will and sorry again
Inside of StateHandler there are two if statements, the first if statement will check if the crouch key is pressed and override the โstateโ variable to crouching. The next if statement, then does a few more checks and overrides the โstateโ and move speed variables to something else. Iโm not sure this will solve your problem entirely however it may fix the issue of the state not updating in the inspector
Inside of the StateHandler Function
Quick question, If i need to have a killzone that resets multiple peoples positino on trigger how woudl i do that? thanks
Like one person triggers it an everyone resets? Or someone triggers it and then only they reset?
one person triggers it and everyone resets
Ah then I would recommend looking into Unity Events, here Iโll post a good video, gimme a sec
thanks!
In this video we take a look at how to build a Custom Event System in Unity. We look at why a Custom Event System might be useful for your game, and the advantages that building one might have over using singletons, or relying on dependencies in the inspector.
Be sure to LIKE and SUBSCRIBE if you enjoyed this guide! Share the video for extra lo...
would this work with 2d too?
Yes
alright thanks
One message removed from a suspended account.
Doesnt line 78 in Wizardy set the reference?
wizardy: https://gdl.space/hequtomome.cs
Magicball: https://gdl.space/alivenifay.cs
You need to configure VS Code !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
have you checked whether it did?
It does set it to something. It could be null.๐คทโโ๏ธ
it shouldnt be null
you mean throw in a debug.log ot see if the code runs?
Checking that there's actually something assigned at that point. Which also checks whether it runs (though presumably it does)
This could also occur if you created an instance another way, or already had one in the scene.
yea cu then movement.isfacingright would throw an error
but it doesnt
but i tell it which instance specifically so how could a nother instance affect it
but there wasnt a second instance
How are you confirming that there's not a second instance of MagicBall in the scene that wasn't created by Wizardy?
You could also destroy the Movement instance to cause this exception
i dont change it/destroy it
only change is giving it a reference with getCOmponent in start() in wizardy
so if it wasn't created by Wizardy then it won't have movement assigned
wait no, there shouldnt be other gameobject woith wizardy
my mistake
only wizardy script can create magic balls and only mages have that script, and there are none of them in the scene, they get spawned in
Then pull out the debugger and take a look at what's happening or not
I bet code running in prefabs is involved somewhere.๐ฌ
The info gets passed into the event
what do i even check for? i have no idea how it messed up it was working before
Check everything, you can see it's null, so you can work your way back and find when that object was created
Any idea how can I fix this?
As nobody really knows what 'this' is or how it works, no
I was explaning... Sorry.
How can I remove the possibility for the ball to move horizontal?
Like I this for a laser that bounces out of walls, it send a raycast to see where it should stop expanding and then at the normal of the wall detection it sends another bounce. Now I want to do this but for bullet instead of continuous laser so it has to happen at the collision with the wall getting the normal of the collision but no idea from where to get that
Is that even possible?
What do you mean? hit.normal is the normal from the raycast, and collision events return a similar structure that also has a normal.
In the case I show, yes it is the raycast normal; I want to do that for a collision, how do I do that?
collisions have points that have normals
and collision events return a similar structure that also has a normal.
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
I am actually using OnTriggerEnter, is that an issue?
Trigger events don't have normals, no
You dont have points with trigger so raycasts is still the idea
with closest point method I think?
it's probably more accurate to just raycast ahead honestly (well, I guess if it gets hit on the sides then maybe the ray wouldn't be ideal)
So.... I should send a raycast just before the collision?
Hi guys, I made a grid and want a way for objects which are following the mouse to follow within the constraints of the grid. I have asked this many times before but I really am not at the stage where I know how to progress after implementing the sized grid, any pointers or ideas would be appreciated
probably should give some idea of your implementation
or what you have done so far with your grid
for some reason only the last one shows that it doesnt have a reference, when i pause, cuz ye a million magic balls spawn for some reason
this is the debug in magicball script
Note how that one is not a clone
hmm it used to be, i tried to improve the code but here we are
thats a good lead i suppose
just made a grid with a correct size, I will have a placeholder which follows the mouse along the grid and will lock to the grid, the placeholder is 5 grid squares tall and one grid square wide. then when the user clicks the mouse, it will place an object at that point. I have implemented everything, apart from the locking to the grid mechanism
wait actually.. what does that tell us?
shouldnt it be a close everytime i instantiate
does that mean its like... trying to access the prefab or somewthing
Sounds like you need some pathfinding alg at this point, because it seems like you want stuff to travel to your mouse pointer depending on the cell that they are in. And, if they cant travel directly to the mouse pointer, then they need to calculate a path using defined routes between each node.
no offence, but that sounds like an overcomplicated solution, all grid cells with give the same constraint to the object
I dont know though I'm just aiming for the easiest solution
You should debug where you assign the reference. It's no point checking it in start as we know that it's missing a reference at some point.
this is what i currently have, i want the placement to lock to the grid cells
So you just want to set the positions to the closest fraction inside a grid?
yeah, just need to find closest point and then have the object just appear in the middle of the cell
not sure how fractions relate to grids as ive never used one but i assume so?
Maybe bad word choice from my side ๐ But in the end, you want to round your numbers to the closest full number inside your grid steps
so instead of a grid i should make a dot matrix kinda thing?
is there no way to leverage my already in place grid
yeahh that sounds right actually
that makes sense to me although never rounded in c#
You might have to refactor your grid script to use round, because rounding is just math to the closest full number. so 1,2,3,4 and so on. But I guess, your grid might be some fancy .5 or whatever number?
If I send a raycast in the same frame that the OnTriggerEnter triggers, would it detect the collision or would it pass trough?
so there is an already in place whole number rounding function, and I could like multiply by the steps my grid are in?
Hopping for something like this
will I understand how to implement for my grid steps via just this?
Is there a reason, you want two things trigger the collision?
It would detect its OWN collision
It would be separate and unrelated to the OnTriggerEnter event
Will I ever be rich af? I dont know, but I can work towards it ๐
Cause everything works on Trigger but I need a Physic normal
had to ask while your here cause im bout to sleep
public Vector3Int GetTileIndexFromWorldPoint(Vector3 worldPoint)
{
Vector3Int index = Vector3Int.zero;
var localPoint = transform.InverseTransformPoint(worldPoint);
var chunkIndex = GetChunkIndexFromWorldPoint(worldPoint);
localPoint.x -= (chunkIndex.x * tilesPerChunk.x);
localPoint.y -= (chunkIndex.y * tilesPerChunk.y);
localPoint.z -= (chunkIndex.z * tilesPerChunk.z);
index.x += (int)(localPoint.x / tileScale.x);
index.y += (int)(localPoint.y / tileScale.y);
index.z += (int)(localPoint.z / tileScale.z);
//We should probably check valid index bounds eventually just incase of percision errors
return index;
}
Some code from my voxel thing I was making with grid but similar idea to how to get the index
What do you need it forM and why is everything a trigger?
Well, that is indeed a normal way to handle it when avoiding normal collisions
Oh, ignore the chunk stuff though
if that is just whole number rounding idk the logic behind applying that for my grid steps
It is a trigger cause the bullets don't have any physics, so they just detect triggers. And I need a normal cause I want them to bounce on that direction
get some sleep and try out tomorrow. Test, make mistakes, learn
i get what your saying but I need to leave in 7 hours with a plan
Absolutely, if you have the ambition an patience :)
That sounds kinda weird. no physics but you want them to bounce?
void RicochetAbility(Collider currentHitCollider)
{
Vector3 collisionPoint = currentHitCollider.ClosestPoint(transform.position);
Vector3 normal = (transform.position - collisionPoint).normalized;
Vector3 direction;
//Kind of a bandaid as if the position and contact are too close then the normals zero out
if(normal == Vector3.zero)
{
direction = -transform.forward;
hitRotation = Quaternion.LookRotation(-transform.forward, Vector3.up);
}
else
{
direction = Vector3.Reflect(transform.forward, normal);
hitRotation = Quaternion.LookRotation(direction, Vector3.up);
}
}```
Here's my implementation I've done quite a while ago using triggers only but you can see that comment there which has some problems
That's not weird at all, I want them to move on a straitgh lane doing stuff when they pass though other stuff
If they don't have any physics, triggers won't be a reliable way either. In fact they don't make any difference compared to a collider. And if you don't want the bullets to have any physical presence at all, just use raycasts instead.
I've tried to make a text be constantly changing color, but it doesn't seem to be working, any idea?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FontColor : MonoBehaviour
{
public CanvasRenderer Renderer;
public float timerStart = 2.0f;
private float repeat = 2.5f;
void Awake(){
InvokeRepeating("changeColor", timerStart, repeat);
}
void changeColor(){
Renderer.SetColor(new Color(Random.Range(0, 255), Random.Range(0, 255), Random.Range(0, 255)));
}
}
It just goes back to white ๐
Is that how you get a normal? Wouldn't that make that it always bounces off in the same direction where it collided?
Like image 1 instead of 2?
Im pretty sure I got some of the info from the unity forums and I had it working
are you sure .SetColour takes in RBG values and not normalized?
Or I am just dumb?
Do you guys use Cinemachine for camera? Or create your own, that looks at player at all times, and can move too?
not sure...
!docs CanvasRenderer.SetColor
Depends on the project.
pretty much
So.. what would be the correct method?
thanks
I want the "Brick Breaker" to be changing color
tweening
How do I implement that?
use something like Dotween or do your own Lerp
No, the triggers are not meant to do anything with the bounces, they just are meant to detect when the bullet enters an enemy to deal damage to it or when it does enter a wall to destroy it (since the bounce effect is not by default, is more like a poweUp)
you could just change your random.range to 0f, 1f instead since these are normalized values. this is a very simple solution and wouldn't allow for much customizability though. so i would recommend doing further reasearch.
So if you raycast, you get the hit direction and can calculate the bounce from there, right? Also you can use the ray to shoot the bullet.
Color struct is 0-1 value
Color32 is 0-255
The raycast should only be sent when the bullet is on a wall, you cannot really tell if it is going to bounce there before hand; also I am guessing it consumes less resources
Ok, I booted up and was testing and you're right that it should give me the direction back towards the projectile, but because of the nature of the primitive colliders I was using the hit is never dead-on so it kinda works. The raycast however is the better idea because you do need that surface info usually. I was doing a bunch of things like just assuming my hit was always being reflected as an angle and other things to try to get around not using raycasts.
Other problems I had using raycasts though is you need to cast it a little more behind the projectile otherwise you wont hit what's in front of you. Rather I was having clipping issues a bit without moving it back.
I usually see two kinds of cameras. One that only points at the player, but can move in a sphere ig. Another that does not move, but you can look at something beside the player. Which one do you use?
I mean, the raycast is send from the origin of the proyectile, should work if it is big and slow enough isn't it?
raycast is instant when you query it
I tried 
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class FontColor : MonoBehaviour
{
public CanvasRenderer Renderer;
void Update(){
Color objectColor = new Color(Mathf.Lerp(0, 255, Random.Range(0, 1)), Mathf.Lerp(0, 255, Random.Range(0, 1)), Mathf.Lerp(0, 255, Random.Range(0, 1)));
Renderer.SetColor(objectColor);
}
}
Does not work
I dont understand what I am doing
The text turns black :/
Yeah, I meant slow enough to not overshoot the origin
Color.Lerp please
all sorts of wrong, dont randomly start adding things, you need to look up things you don't understand
On a frame
But you are resetting your color every frame in update
that lerp is completely wrong
I thought that this Mathf.Lerp(0, 255, Random.Range(0, 1)) would make it pick a number from 0 to 255
Please check for Color.Lerp and how to lerp in update
Ideally, you'd cast the ray before the colliders touch if your colliders are relatively small, but that could be taxing.
or just download Dotween and lerping colors is like 1 method, just random change the color you want to fade into @sleek orchid
I just had issues on really fast projectiles and doing ricocheting logic (ive seen it done really nice though so I must been doing something wrong)
I will try the hard way, but I will check Dotween!
Funny... Why do they use this is the documentation? Mathf.PingPong(Time.time, 1)
Why not only 0, 1?
where
ive done that too
Raycasts in general just better for small/quicker projectiles from my experience
because t supposed to be a self-incrementing value
Raycast is just a collision check without any projectile similarity
wait i should prob have one when attacking as well
At the very worst I could just literally instantiate the new proyectile with the rotation of the previous one with an offset of 90 or -90 on the Y axis, since the game is basically on a 2D plane
What's the component in TextMeshPro that has the color?
pretty sure its just .color
also its a property not a component
I was overcomplicating, I had a read and I think I will be able to do it now
hiihi
Thanks, m8 โค๏ธ
nvm i think i found the problem
LESS GO!
I found a solution to the lambda stuff from a few days back,
void AddCards()
{
for (int i = 0; i < cards.Length; i++)
{
Instantiate(cards[i], gridLayoutEmpty.transform);
var local = cards[i].gameObject.GetComponent<Image>();
MyAction += () => { CardList(local); };
}
}
void CardList(Image local)
{
cardList.Add(local);
}
}
now i can use and compare the sprites much easier ๐
couple of things to be improved
๐ You just made a little spaghetti function for the same result in your lambda ๐
unaccepttaaaaabbaaaleeeee!!!!
I kept feeling like i was rewriting the same thing in a different way, but idk how
to be clear, you can just capture the index https://unity.huh.how/anonymous-methods-and-closures#resolution
The more i think about the more editor friendly having the sprite show/change in the editor, its a memory matching game, so comparing two cards would be ideal. But yea ill look at that
it made me more confused :{
I use Scriptable objects for mine
Id love to use a scriptable object ๐ฎ
makes match comparison that much cleaner
i want to be able to turn on and off an image, basically the front and back of a card, and when you click on it it flips, waits for a second card, then flips back over if wrong, or stays up if right
i watched this doodoo tutorial and a few more with weird, badly formatted ways to code it
nice made this for a jam a few days ago
ill play it
It demoralizes me that a mechanic this small of a baby card game is tripping me up so bad
there are many ways to do something thats why
//on the tile
public void Flip()
{
IsFlipped = !IsFlipped;
image.sprite = IsFlipped ? data.Sprite: coverSprite ;
}```
What's a scriptable object?
in short, it lets you create your own kinds of assets
ScriptableObjects are unity objects, but they aren't components -- they aren't attached to game objects
They're much more like a Material
is there a way to mark an object as not inhereting rotation from its parent
Not really. You can apply counter-rotation, or make a new parent so that the previous parent and child are both children of a common parent
Or just forego parenting and have the previous child update its position based on the position of the previous parent (if that's the reason you wanted it to be a child)
hm can I directly override the rotation
I seem to be able to set the rotation
but not use LookAt
//flashlight.transform.LookAt(hit.point);```
top line works but the next just doesn't
like it rotates but it doesnt look up or down for some reason
Have you logged hit.point to see where it is?
ah its not looking up or down either lol
I fixed the hit point and it still isnt working
wait
maybe not one sec
ok I think it works :D
Glad it works. Never really heard back about if you logged the value though... ๐
Probably would have been helpful to know it
does anyone know how to make things like auto game saving, like gacha games, and you can login with your google account?
you can use something like Unity authentication has google built in
Ohh I see, is it like unity cloud?
its part of the whole cloud eco system so cloud saving, leader boards etc
Having some issues with scene loading (first time trying to actually switch scenes, start menu -> game), it doesn't seem to nstantiate a slew of game objects when loading the 'game' scene, but they load fine when running the game scene directly
not enough info
!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.
void Update()
{
ChangeScene();
}
public void ChangeScene()
{
if (SceneManager.GetActiveScene().buildIndex == 0 )
{
if (Input.GetKeyDown(KeyCode.Return))
{
StartCoroutine(LoadScene());
}
}
}
IEnumerator LoadScene()
{
Scene currentScene = SceneManager.GetActiveScene();
var myListeners = GameObject.FindObjectOfType<AudioListener>();
Destroy(myListeners);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(gameScene, LoadSceneMode.Additive);
while (!asyncLoad.isDone)
{
yield return null;
}
// SceneManager.MoveGameObjectToScene(this.gameObject, SceneManager.GetSceneByName(gameScene));
SceneManager.UnloadSceneAsync(currentScene);
}
So i load my scene with the following code
And there is some code used to instantiate a bunch of blocks (Bounds Block game object), in a list called 'BoundsBlocks'
function for the block instantiation looks like this
private void InitBoundsBlocks()
{
int startY = (int)Math.Round(transform.position.y);
for (int y = startY; y < startY +25; y++)
{
for (int x = (int)transform.position.x-1; x < transform.position.x +11; x++)
{
if (y == startY|| x == transform.position.x -1 || x == transform.position.x + 10)
{
GameObject bb = Instantiate(boundsBlock, new Vector3(x, y),Quaternion.identity);
print("bounds block active? : " + bb.name.ToString());
boundsBlocks.Add(bb);
}
}
}
}
I've confirmed the bounds block code itself runs (that print after the instantiate runs for all 60 iterations as expected)
So after scene load, the list shows that it has 60 elements, but all references to the boundsblock game object are missing:
It almost seems like the instantiation is happening, but then the game objects are getting destroyed?
Too much info, or not enough?
I should also say, the print Shown in the InitBoundsBlock code shows the instance actuallly exists in the moment after instantiation, showing a name of "Bounds Block (clone)". So I'm scratching my head a bit here.
All I could think of is the objects arent being tagged DontDestroyOnLoad but you're loading async (additive) so I'm not too sure
Does running instantiate in any of the Start or Update functions imply that they are being created after the load finishes regardless? I don't know myself
I don't usually load additive so I'm not too sure but worth a shot at tagging em
Tagging them?
MAybe it wasn't the help you thought you were giving, but you've fixed my problem lol
I hella simplified the scene change code so I wasn't doing the additive load stuff or async etc, and... it just works
public void ChangeScene()
{
if (SceneManager.GetActiveScene().buildIndex == 0 )
{
if (Input.GetKeyDown(KeyCode.Return))
{
SceneManager.LoadScene("Game");
}
}
}
Considering my use case (literally just making a tetris clone to get some practice in), this is probably more than fine
@timber tide Thanks

Always gotta remind myself to Keep It Simple, Stupid.
whats the diffferent between tilemap.tile and tilemap.tilebase?
Google it
TileBase can implement different type of tiles, where Tile implements TileBase as one of these types.
what is better, make isOnGround with collisionenter2d or make ray/box below char and checks their collision
rays/box
what is the way to go bout shooting bullets
do i use a ray cast or actual bullet prefab and instantiate?
depends on how you want your game to feel. there is no "correct" answer
This-ish (don't need to be DDOL). You need to set the newly loaded scene as the active scene, before you spawn anything.
Instantiated objects get spawned in the active scene, so you're spawning the objects in your menu, then they get destroyed when you unload the menu scene
@clever pasture โ๏ธ
any idea what most popular games do it?
again, there is no single answer to that. it entirely depends on the game. but using raycasts is typically called "hit scan" and actual instantiated bullets is "projectile" so look up your favorite games and see which of the two methods those games use
` public void OnPointerDown(PointerEventData eventData)
{
rectTransform.sizeDelta = newSize;
}
public void OnPointerUp(PointerEventData eventData)
{
rectTransform.sizeDelta = originalSize;
}`
this is a script to increase size of the button when touched , it does the work , is visibly larger , but it calls onPointerUp method when i drag my touch outside of the older smaller Size ,
So you want your user to be able to touch the button, but then drag the touch away and the button remain active?
i want that when user touches the button , it becomes larger in size until the player removes the touch or goes outside the bounds of new button size while dragging
Ah got it, your UI is not reacting to the updated size. Just for curiosity, did you try to use the scale instead of the sizedelta and see if that issue persists?
just did it , and yes same results .
void Start() {
rectTransform = GetComponent<RectTransform>();
originalScale = rectTransform.localScale;
}
public void OnPointerDown(PointerEventData eventData)
{
rectTransform.localScale = newScale;
}
public void OnPointerUp(PointerEventData eventData)
{
rectTransform.localScale = originalScale;
}```
it's three backticks for code btw, not just one
are you sure, you are resizing the button and not just some child image of the button or similar?
three backticks and 'cs' after the top ones
yea its the button , see in the image , the scale goes 1.5f after clicking it .
and this line
rectTransform = GetComponent<RectTransform>();
ensures its the recttransform of the attached gameObject
its visibly scaled 1.5f , but not functionally
"Always" keep UI scale to 1,1,1 .. use the width/ height fields to change the size
It was just a test suggested to see, if its not resizing the wrong thing.
I could think of the layout not being rebuild immediately and therefore working with old values in the hit checks. Did you try to rebuild the layout after resizing?
For some reason after adding new stuff to a level of my game the spawn system suddenly stopped working.
I tried everything i know to attempt to fix it but didn't see what was causing it to fail like this; I tried putting a normal float instead of Delaytime, put WaitForSecondsRealtime, checked if the script was still running when it was triggered but no answer
Did i suddenly do something wrong in the code or is this a matter outside of scripting?
(It stops exactly at waitforseconds, which is usually set to 0.5f)
IEnumerator SpawnWithDelay(float DelayTime)
{
print("Called with delaytime " + DelayTime);
yield return new WaitForSeconds(DelayTime);
print("spawning after waiting");
SpawnWave(1);
ArenaActive = true;
if (WillTriggerGlitchOnceDead)
{
GameObject.FindWithTag("musichandler").GetComponent<musicHandler>().CanGlitch = true;
GameObject.FindWithTag("Glitch").GetComponent<CauseGlitch>().CanBeTriggered = true;
}
}
how do you start the coroutine?
private void OnTriggerEnter(Collider Collission)
{
if (!Triggered)
{
if (Collission.gameObject.tag == "PlayerCollider")
{
if(TriggersArena)
{
for(int i = 0; i < DoorsToLock.Length; i++)
{
print("Door locked");
DoorsToLock[i].GetComponent<Door>().TriggerArena(true);
}
print("spawning with delay");
StartCoroutine(SpawnWithDelay(0.5f));
} else
{
print("spawning wave");
SpawnWave(1);
}
}
Triggered = true;
}
}
The prints have confirmed Spawning with delay and Called with delaytime
your coroutine is only delaying your logs. it does not delay anything outside of it
there's a bunch of more code inside the coroutine but that's currently besides the point. It's not even printing spawning after waiting
please do not edit the code when sharing for troubleshooting. how could we possibly know if something else is causing an issue? and have you checked your console for exceptions
I tried running it and all there is is this
(the first spawning after waiting is because of a previous chunk that triggers using the same script which oddly enough did work)
so spawning after waiting is working once?
screenshot the entire console window. and make sure that the object you are starting the coroutine on isn't being set inactive or being destroyed
On another object? whats the delaytime on that. is delaytime probably public and oyu set it to something higher in inspector?
the coroutine isn't being destroyed nor set inactive
it has no public variable; it's always 0.5 (as seen in the collision void)
i mean, there are 0 logs after the last (second) time the coroutine is started. are you absolutely certain that nothing is preventing the coroutine from running like the object being disabled/destroyed or the game being stopped?
I see nothing in the editor of it being disabled, destroyed and the game isn't being stopped either; I can still freely move around in the game even after it happens
Simple fixes like restarting the computer and what not? Its just a weird behaviour and your script seems to be fine
normally my pc doesnt really affect it but ig i could try
restarting didn't really fix it but now i magically have 2 new errors (turns out one of those errors was about the profiler)
check your code for StopCoroutine calls and put a log in that object's OnDisable method to make sure it isn't actually being disabled
My entire game only has 2 scripts with StopCoroutine which disable coroutines in their own scripts (which isn't the script that's failing), and those calls don't get triggered at the part where the spawner breaks
So i don't really see how that could be the cause of it
and how was i supposed to know that? you've not even bothered sharing the full code for the class isn't working.
i see you haven't bothered trying my second suggestion
yeah cause i didn't see the logic in it if there was no StopCoroutine in the failing class
StopCoroutine has nothing to do with an object being disabled
so if you're just not going to follow troubleshooting instructions, i'm just not going to attempt to help you further
Look i have a brain the size of a peanut is this what you wanted me to do; this is what happens when i put an onDisable in the said script
wow crazy how i was right all along that the object is being disabled
no need to rub it in
lmao @golden canopy why are you so pressed you got an issue and hes just trying to help you
https://paste.myst.rs/n10vqxym
yesterday i tried to split a script into two parts as it was getting too big, but this caused some problems; two line of code aren't working properly
the lines are spriteHeight = spriteRenderer.transform.localPosition.y; which just isn't doing it and Debug.Log((int)entityHeight); which is always inputting zero when that's just blatantly wrong. Both of these lines are in the new PlayerHieghtEntity script.
saying this again as i can't figure out the problem
a powerful website for storing and sharing text and code snippets. completely free and open source.
first off you have nested if-statements
but try what was suggested so we can identify the problem
the problem was already identified. they are deactivating the gameobject somewhere
turns out it was my own stupidity forgetting to replace a required gameobject
2 doors were basically fighting with each other about keeping the chunk active or not
cause as i said, my brain's the size of a peanut
I'm trying to render particles on a "render texture" and I want to make it transparent.
How can I make this texture transparent?
I want to change the alpha value but I can't find it.
This is how the render texture is with my camera set to alpha 255.
The other picture is how the render texture is with my camera set to alpha 0.
The material of the particles isnt transparent so it isnt rendering.
i made movement with addforce force and jump with addforce impulse, and now my character is faster when jumping then when he is walking, how can i fix it?
The floor likely has friction so you'll always fly faster than slide
for some reason this isnt detecting the collision, i dont get anything back in the console and im completely stumped. I thought it was because the collider for the enemy tag doesnt actually touch the player, but when i set it to a trigger, nothing changed
public class EnemyCollision : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.tag == "enemy") // checks for collision with specific tag
{
Debug.Log("collision");
HealthManager.health--; // calls health from other script
if (HealthManager.health <= 0 ) // checks if health is 0 or less
{
// game over screen
}
else // player is not dead
{
StartCoroutine(GetHurt());
HealthManager.health -= 1; // reducing health by 1
}
}
IEnumerator GetHurt()
{
Physics2D.IgnoreLayerCollision(8, 9 , true); // ignoring collisions between 2 layers
yield return new WaitForSeconds(3); // 3 second timer
Physics2D.IgnoreLayerCollision(8, 9 , false); // stops ignoring collisions between 2 layers
}
}
}```
also you should be using the CompareTag method rather than string equality when checking an object's tag
well i was copying a youtube video and it seems to be working for them
that doesn't mean it's correct
Log the name and tag of what you hit
Does anyone have an idea on how I could make this shader transparent?
this is a code channel buddy, #archived-shaders or #๐ปโunity-talk for general material questions
i have this now
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy")); // checks for collision with specific tag
{
Debug.Log("collision");
HealthManager.health--; // calls health from other script
if (HealthManager.health <= 0 ) // checks if health is 0 or less
{
// game over screen
}
else // player is not dead
{
StartCoroutine(GetHurt());
HealthManager.health -= 1; // reducing health by 1
}
}```
and its thrown up 222 warnings
and what do they say?
possible mistaken empty statement, and then about 200 of them say "the referenced script (unkown) on this behaviour is missing"
wiat a minute
yep, do you not see the squiggly line in your IDE?
yeah i had a ; after the if statement
got rid of it but the warnings havent disappeared
well the first has one not the rest
the rest of the warnings are not related to this code. you either have a compile error that broke some of your components or you renamed or moved a component without its meta file being updated too
{
canShoot = true;
}```
is this the correct way to check a rotation has been met
no, a rotation axis is a float, it's highly unlikely you'll ever get an exact match, when rotating between two rotations
what would be the best approach to checking this via a float
to allow for a rounded reading
it depends on the context
the player is rotating the cannon to a max (or "desired") rotation
upon reaching this rotation on the Z, they can shoot
mouse movement
the cannon will also lock in position
interactive cutscene ig
you almost never want to rely on the eulerAngles for logic. they are interpreted from the rotation quaternion at the time you read them and can be different from what you expect since the same rotation can be represented in a number of ways in euler angles
you can try having an invisible collider to where the cannon needs to point and shoot a raycast and lock the canon if it hits that collider
yeah could do actually
thanks
understood thanks! ill avoid them
Hello, while I was trying to build with IL2CPP in Unity, I got a error like this. It wants me to install Visual Studio, but I use vs code and I have never encountered such a problem before.
did you scroll down to see what all the options for what you must have installed are?
yes
then install one of the options because it is required for IL2CPP
it want install visual studuo 2017 or newer version
ok ,I try thanks
script runs now but on contact i immediately lose 2 lives instead of 1, do you know a way i could fix this?
does either object involved in the collision have more than one collider?
ah yes my player is a circle collider and a box collider
two colliders touching another collider == two OnCollisionEnter calls
yes i understand that, how do i make it so its only affected by the circle collider
either remove the other collider or put it on a layer that does not collide with the other object(s)
Hi!
Im following this tutorial:
https://catlikecoding.com/unity/tutorials/mesh-deformation/
I want the mesh to stay in the deformed shape.
At step 4.2, when a force is applied, the mesh starts to deform but I havent found a way to stop the deform without going back to the original shape. Even if I can slow it down it's still moving forever. The only way I made it work was by adding a return in the update but I feel like it might not be optimal (and also it didnt work that well)
I want to be able to deform the shape at runtime cause I'm trying to make a pottery game in VR for a game jam. The way I see it there would be tiny invisible spheres at the tip of the fingers which could deform the shape when theres a collision.
I'm sorry, I've tried to come up with my own answer but I feel like I don't even know where to start and everything I try seems futile because my understanding of the subject is limited.
If anyone could help me with this matter I'd really appreciate it.
Thank you so much! I'll add the code
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshDeformer : MonoBehaviour {
public float springForce = 20f;
public float damping = 5f;
Mesh deformingMesh;
Vector3[] originalVertices, displacedVertices;
Vector3[] vertexVelocities;
float uniformScale = 1f;
void Start () {
deformingMesh = GetComponent<MeshFilter>().mesh;
originalVertices = deformingMesh.vertices;
displacedVertices = new Vector3[originalVertices.Length];
for (int i = 0; i < originalVertices.Length; i++) {
displacedVertices[i] = originalVertices[i];
}
vertexVelocities = new Vector3[originalVertices.Length];
}
void Update () {
uniformScale = transform.localScale.x;
for (int i = 0; i < displacedVertices.Length; i++) {
UpdateVertex(i);
}
deformingMesh.vertices = displacedVertices;
deformingMesh.RecalculateNormals();
}
void UpdateVertex (int i) {
Vector3 velocity = vertexVelocities[i];
Vector3 displacement = displacedVertices[i] - originalVertices[i];
displacement *= uniformScale;
velocity -= displacement * springForce * Time.deltaTime;
velocity *= 1f - damping * Time.deltaTime;
vertexVelocities[i] = velocity;
displacedVertices[i] += velocity * (Time.deltaTime / uniformScale);
}
public void AddDeformingForce (Vector3 point, float force) {
point = transform.InverseTransformPoint(point);
for (int i = 0; i < displacedVertices.Length; i++) {
AddForceToVertex(i, point, force);
}
}```
void AddForceToVertex (int i, Vector3 point, float force) {
Vector3 pointToVertex = displacedVertices[i] - point;
pointToVertex *= uniformScale;
float attenuatedForce = force / (1f + pointToVertex.sqrMagnitude);
float velocity = attenuatedForce * Time.deltaTime;
vertexVelocities[i] += pointToVertex.normalized * velocity;
}
} ```
public class MeshDeformerInput : MonoBehaviour {
public float force = 10f;
public float forceOffset = 0.1f;
void Update () {
if (Input.GetMouseButton(0)) {
HandleInput();
}
}
void HandleInput () {
Ray inputRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(inputRay, out hit)) {
MeshDeformer deformer = hit.collider.GetComponent<MeshDeformer>();
if (deformer) {
Vector3 point = hit.point;
point += hit.normal * forceOffset;
deformer.AddDeformingForce(point, force);
}
}
}
} ```
This code is written to keep track of the forces and continually apply them every frame. There's no reason to do it this way if you just want to apply a force while the user is holding down the mouse button. If you're uncertain on how to do that, I would suggest you look for another tutorial that better matches your end goal.
Honestly it's true it's probably gonna be easier to start from another tutorial,
Thanks!!
Awesome thanks for the explanation, I was thinking something like that was happening but I didn't know enough about scene loading to know exactly what was up. Next time I try async scene loading I'll try this out
I have a bug, when I look with my camera down, I see the leg of the character...
So does anyone know how to fix this?
this is a code channel, what's the code question here?
Ahhhh, is there a special channel for camera problems?
I doubt that's a camera problem.. it's a setup problem. id:browse to find channels in future, though this question can probably just go in #๐ปโunity-talk (after you delete from here so you don't get told off for crossposting)
ok thanks
Hello everyone. My normally running script gets deactivated for no reason. What would be the reason? I know that sometimes there is such a problem on the internet when code is written into the awake function, but when I write code from the awake function into the start function, it is not deactivated, but none of the lines of code work. How can I solve this problem? Thank you very much to everyone who has helped already.
check your console for errors and resolve those errors
One message removed from a suspended account.
One message removed from a suspended account.
Pick one problem at a time and focus on that before moving on to another one.
One message removed from a suspended account.
ok so you'd have to show how that is supposed to work and what objects and scripts you've set up for that to work
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Well checking the distance to the player doesn't make much sense for a big "killzone" kind of thing
you'd have to be at exactly the pivot of the object for that to work
A better option would be to use a big trigger collider and OnTriggerEnter
One message removed from a suspended account.
What part are you confused about?
One message removed from a suspended account.
I'm talking about your whole strategy
One message removed from a suspended account.
One message removed from a suspended account.
Thank you. When I looked at the console, it said that it was not working because I closed a UI element, and it worked.
Is there a way to modify this script for it to work?
Sure, by completely changing how it works.
I thought I could basically take the script for the enemy reset and just put it on something else and have it not move
But if you think about how your enemy works and how the "kill zone" needs to work, that doesn't make very much sense.
Here's an example you can learn about trigger colliders:
https://www.youtube.com/watch?v=m0fjrQkaES4
Watch this video in context on Unity's learning pages here -
http://unity3d.com/learn/tutorials/modules/beginner/physics/colliders-as-triggers
How to use a Collider as a Trigger (also known as a Trigger Zone), in order to detect when an object is within a particular space in the game world.
Help us caption & translate this video!
http://amara...
One message removed from a suspended account.
Where did you get the idea to use Invoke. Where did that even come from
No idea where you got OnTriggerEnter.Invoke(); from
Hey short question, lets say I have following code:
if(cheapComparison() || expensiveComparison())
{
//
}
is it faster to write it this way:
if(cheapComparison()
{
if(expensiveComparison()
{
//
}
}
I guess the question I have is if the first case always computes both comparisons or if it skips the second one if the first one has a definitive answer.
One message removed from a suspended account.
One message removed from a suspended account.
The || operator skips the second one if the first is true.
If you want both to always run you would use the | operator
The first case does not run both functions. If the first one is true, it skips the second
thanks for the fast replies
|| short circuits so if the first condition is false it does not evaluate the second condition.
in your second case it only checks the second condition if the first is true
๐ฆฅ
ah but you see, i added extra info about how that second one is not the same as the first
Fair enough, actually. The second condition is actually an AND, while the original is OR
you usually call Invoke on delegates, like public event Action onPlayerHit;
โฆ
onPlayerHit?.Invoke();
ah yeah, seems they are confusing the delegate's Invoke method with MonoBehaviour.Invoke which is used to call a method via reflection after a delay
and, to be clear, you want to use MonoBehaviour.Invoke extremely rarely if at all
Hi anyone know why there is seems when i move around
using a tilemap
for the walls
what is the problem?
Not a code problem - but you need to look into the Pixel Perfect camera
does pixel perfect camara work with cinema camara
also make sure you use a sprite atlas, and set compression settings properly for your sprites
you don't actually need the pixel perfect camera to fix that. sprite atlases for your sprites should do the trick on their own
my game has a ton of pixel art, and no pixel perfect camera is needed
but sprite atlas is crucial
need atlas and proper compression settings, or else
hi what is a atlas
a sprite atlas is like one generated image file that maps out a ton of sprites
you can have like 1000 PNG files with various numbers of sprites
an atlas is basically one image file that condenses a bunch of them, and for some reason unity isnโt that smart at figuring it out without being explictly told
ask google how to set it up
when the GPU draws a sprite, it needs to have a texture to read the pixel data from
the naรฏve approach would be to just upload hundreds and hundreds of tiny textures to the gpu
a few big textures are easier to deal with
Do i list my existing tilemap for packing?
void OnColliderEnter(Collider obj)
{
if(Input.GetKey(KeyCode.Space))
{
if(obj.CompareTag("Wall"))
{
rb.useGravity = false;
}
}
}
the console doesnt show any error still this isnt working i tried adding a debug but still does not respond any reason why?
OnColliderEnter isn't a thing
you made that up
๐ญ
my bad
but i cant use collider with on collision and if i use collison then compare tag doesnt work
It might help if you went and read the documentation about the API's you are using
hi, i have tried this just now, i cannot use sprite atlas inside my tile palette, it doesnt let me drag anything other than sprites into it.
Hello, i updated my unity version and now when i double click on debug.logs in the console it doesnt show or direct me to the line of the Debug.log
has this changed?
also the stack traces look much larger and low level
You are probably seeing an error in compiled code that isn't actually yours to access, which is also why it's not opening the file
Show the stacktrace
what do you mean? i wrote the debug logs
Show the stacktrace
it literally changed how they used to look and behave when i click on console
it never showed like this for me
and if i click it doesnt lead me to the place this code is
I think this has to do with the burst compiler, there might be a way to disable it
Try Project Settings -> Burst AOT Settings -> Disable Burst
https://docs.unity3d.com/Packages/com.unity.burst@1.0/manual/index.html
Hey guys, have any of you used the Offscreen Target Indicator pack on the store ?
Is there a guidance document on how to use this pack ?
there is a function which finds the nearest object with a tag right?
No, there's a function to find a thing with a tag, and a function to find all things with a tag
why would i want to disable burst?
Because that's the thing that's making your stack traces harder to read from what I can find
ive always had it, and i need to use it
the only thing that changed was the way Debug.log shows on console
after updating unity
void SideCheck()
{
if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.right)*hit_distance,runnable_wall))
{
if(!wall_running)
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.useGravity = false;
wall_running = true;
rb.AddForce(Vector3.left * jump_force * Time.deltaTime,ForceMode.Impulse);
}
}
else
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.left * jump_force * Time.deltaTime,ForceMode.Impulse);
}
}
}
else if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.left)*hit_distance,runnable_wall))
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.useGravity = false;
wall_running = true;
rb.AddForce(Vector3.right * jump_force * Time.deltaTime,ForceMode.Impulse);
}
}
else if(!Physics.Raycast(transform.position,transform.TransformDirection(Vector3.left)*hit_distance,runnable_wall) || !Physics.Raycast(transform.position,transform.TransformDirection(Vector3.right)*hit_distance,runnable_wall))
{
rb.useGravity = true;
Debug.Log("FALSE");
wall_running = false;
}
}
this is the logic i m using but for somereason the ray cast is hitting the object even from really far even if the hit_dictance is = 0.001
why is that
max distance is a separate parameter in Raycast
not something you multiply into the direction vector
check the docs
you're likely plugging the layermask into the max distance param right now
so to find the nearest id find all then loop until i find the nearest
GameObject allChildren[] = new GameObject[frame.transform.childCount]; why does this give me an error? i am trying to make a gameobject array inside of a function
Or get all objects within an area and see which of them have the tag, depending on how many objects with that tag there are and how big the area is, one of them is probably better but there's no way to know which without knowing the full context
what error
Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
i know the if statement is unfinished, but why is points.count not valid
and nearestpoint
Ah, wait, that's the wrong way to do an array type in C#, it'd be GameObject[] allChildren =
yeah i just realised ty for the help
Arrays have .Length not .Count
ohh right
void SideCheck()
{
if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.right),hit_distance,runnable_wall))
{
if(!wall_running)
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.useGravity = false;
wall_running = true;
}
}
else
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(transform.forward * jump_force * Time.deltaTime,ForceMode.Impulse);
}
}
}
else if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.left),hit_distance,runnable_wall))
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.useGravity = false;
wall_running = true;
}
else
{
if(Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(transform.forward * jump_force * Time.deltaTime,ForceMode.Impulse);
}
}
}
else if(!Physics.Raycast(transform.position,transform.TransformDirection(Vector3.left),hit_distance,runnable_wall) || !Physics.Raycast(transform.position,transform.TransformDirection(Vector3.right),hit_distance,runnable_wall))
{
rb.useGravity = true;
wall_running = false;
}
}
this is my wall running logic anyone who can sugget me a way i can make it so that the player moves up and down the wall like if i m looking up and holding w it moves up the wall
your project needs a sprite atlas so unity knows how to render. you do not add the sprite atlas to your tile palette
sprite atlas references image files (which have sprites). Unityโs inspector lets you define sprites also from those image files.
I forget how to rig it up, but something else in unity references the sprite atlas to render
ah i see, i have since fixed this problem anyway, thank you for your help tho, it turns out it was indeed import settings.
"generate mipmaps" seems to have caused me some problems
also check build. Sprite atlas is not an optional thing when using sprites
it might not be the cause of this problem, but it will be important
so you might as well do it now
Is there a way to track how an object gets deleted in debug?
bump
as in like check how and why the object got deleted, where destroy got called etc
whats the use case
Put a log in OnDestroy. The stacktrace should show you what called destroy on the object
Presumably, for debugging. Sometimes you just don't know where an object's getting destroyed and it's causing issues
true true, just making sure its not some xy thing
I have A and B gameobject. what will happen if i multiply A rotation by B position?
I've been seeing you bump this for quite a while but haven't offered anything because it looks like a pretty complicated setup but since no one's gotten to it I'm going to give it a once-over and see if I can find out what's going wrong
You'd get a really weird-ass rotation
ok thanks ๐
is there a way to get a certain gameobject inside of a gameobject array by its name?
yes iterate over the array and check their names
yes your script is mixing so many things
also looking for a Tag when you have an Interface ? its pretty redundant
thought there might be an easier way but okay ty
easier way is to use a dictionary i guess
First thing I notice is this if statement:
if (inventory.Count > 1 && !isAnimating)
It makes sense to check for more than one item, but I think when you throw the first item away, it removes it from the list, meaning the count is down to 1 and this doesn't run. Maybe instead of removing it from the inventory, you can replace it with a temporary "Blank" object that you clear out when you change away from it
Or, just change the if, and add in a boolean for isNothingEquipped that checks if your hands are empty
if ((inventory.Count > 1 || (inventory.Count > 0 && isNothingEquipped)) && !isAnimating
alright ill have a go thanks
sorry kind of a noob but how would i see this stacktace
check the console at the bottom
and click on the debug message
if(Input.GetKeyDown(KeyCode.Space))
{
Vector3 forwardDirection = Quaternion.Euler(0f, mainCamera.transform.eulerAngles.y, 0f) * Vector3.forward;
rb.AddForce(forwardDirection * jump_force * Time.deltaTime,ForceMode.Impulse);
}
i m using this so the player jumps in the direction where the camera is facing but its not wrking any help?
looks like the stacktrace doesnt show what called destroy on the object
Aw dang it doesn't show it. I thought it did, maybe that's only for DestroyImmediate?
maybe it shows it when it throws an error
rip
For a component that has some attributes, how does one edit those in code with some custom script? Say I wanted to change some number value in a component in a script. How do i do that? I know its like the most basic thing but ive not done unity in forever. Ignore me if i clog up chat
There's a thought. Let's force an error then.
@neon marlin try this instead of a log in onDestroy:
GameObject n = null;
n.SetActive(true);
anyone know why nearestPoint gives me an error
use of uninitialize variable
nope sadly
just says null reference and the line
Dang
maybe there's a setting to show traces in more detail?
What is nearestPoint whenever Points is empty?
but Points won't be empty as it's given items in 'Points = GameObject.FindGameObjectsWithTag("Points")
for min/max stuff i suggest you to use the first array element for "default value"
eg
int min=arr[0];
for(int i=1;i<arr.Length;++i){
min=Mathf.Min(min,arr[i]);
}
then there is no uninitialized local variable
that worked tysm idk how i didnt think of that
ohh sorry didn't know you were talking to me
is this for me?
I don't know how those functions work
try to breakdown your script to something less overconvoluted
did u try ctrl+f searching for "destroy" in your entire project?
How would i do that?
i think the scene is loading after the object is instantiated, idk how to prevent it though
it works fine if i remove the call to loadscene
I do ctrl shift f in visual studio code and it searches your whole project- itโs really helpful
your script is called "PlayerInteract"
but its doing 100 different things..
True
Can I ask a DOTween related question here?
MyScript.UnityEventThatPassesBool.AddListener(delegate { MyMethod(boolFromEvent) });
What's the syntax for accessing "boolFromEvent"?
btw here for example
if (interactObj != null && interactObj.CompareTag("Inspectable"))
{
interactObj.GetComponent<IInspectable>()?.Inspect();
}```
can be simply
```cs
if(interactObj == null) return;
if (interactObj.TryGetComponent(out IInspectable inspectable)
{
inspectable.Inspect();
}
And how does the code know that
yes, also dont ask to ask ๐ just ask
Also, that absolutely can be empty. What happens when there's nothing with that tag?
Ah sorry okay. ```
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class LoadingProgressBar : MonoBehaviour
{
private Image image;
private void Awake()
{
image = transform.GetComponent<Image>();
}
private void Start()
{
image.DOFillAmount(1, 10);
}
private void Update()
{
// image.fillAmount = Loader.GetLoadingProgress();
}
}
I could not find anything about how DOFillAmount is used i thought it was like this.
I'm trying to imitate a fake loading screen because the actual loading takes too little time to show my loading screen ๐
whats the fill amount set to in the inspector? it should be 0
Yeah this solved it. I am trying to make this right since yesterday.
Oh my god I am so sorry.
no problem! and no need to apologize ๐
bump
also https://dotween.demigiant.com/documentation.php you can check this if you wanna know more about dotween's methods
DOTween is the evolution of HOTween, a Unity Tween Engine
Yeah I check the documentation but it just says well this takes this value and to this end value. I mean it is more than enough but I was so dumb to not think about the inspector value ๐ฆ thanks for your time !
UnityEventThatPassesBool.AddListener(MyMethod)
Hello, I'm currently trying Unity for the first time, to make a 2D platformer (i suck rn) and i got my guy to move and jump, but if i hold down jump he'll just fly off into spece, would anyone know how I can add a cap to the amount of times he can jump? (just once) here's the code so far: (it's C#)
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.Space))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
I've been using "delegate {}" every time I add a listener, whether or not the event has a parameter. Is that, fine? Could I leave that off?
Pretty sure I've never actually used delegate {}. It's either a function that already fits the specification, or an anonymous lambda function
So it just needs a null check for nearestpoint
It needs to have a value in the case your loop doesn't run
As a newbie should I be doing a regular 3d project or a 3D URP project?
I've been following tutorials. The first one didn't use URP but cut off part way through (they just stopped makings vids), found a more comprehensive tutorial but it's using URP
I suppose I'm going to upgrade my project to use URP so I can keep following
it should not change anything particular how you code/make game
mainly the materials need to be converted
oh and it has its own Post Processing included so old package should be removed if present
hi, this should be 1-minute fix, it never happened to me before when doing that
using System.Collections.Generic;
using UnityEngine;
public class EndTheTurn : MonoBehaviour
{
private ChessGameController controller;
private BoardInputHandler boardInputHandler;
void Awake()
{
boardInputHandler = GetComponent<BoardInputHandler>();
}
void Start()
{
controller = FindObjectOfType<ChessGameController>();
if (controller == null)
{
Debug.LogError("ChessGameController not found in the scene!");
}
}
public void EndTurn()
{
if (controller != null)
{
ChessPlayer activePlayer = controller.activePlayer;
controller.GenerateAllPossiblePlayerMoves(activePlayer);
controller.GenerateAllPossiblePlayerMoves(controller.GetOpponentToPlayer(activePlayer));
boardInputHandler.SetMoveDone(true);
if (controller.CheckIfGameIsFinished())
{
controller.EndGame();
}
else
{
controller.ChangeActiveTeam();
}
}
else
{
Debug.LogError("Controller is not initialized!");
}
}
}```
EndTheTurn.EndTurn () (at Assets/Scripts/Input System/EndTheTurn.cs:33)
UnityEngine.Events.InvokableCall.Invoke () (at <88d854ea2c91426ebc464f01cd71aa85>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <88d854ea2c91426ebc464f01cd71aa85>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)
so it doesnt read the variable from other script
boardInputHandler.SetMoveDone(true);
any idea why?
other script with exact same things reads normally
we cannot even read line numbers here dude
large code needs links !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.
that is why i pointed problematic line
rest is for context only
i get it cannot access, but idk why
so boardInputHandler is null
yep
find out why
show where you assign it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Board))]
public class BoardInputHandler : MonoBehaviour, IInputHandler
{
public bool MoveDone = true;
private Board board;
private void Awake()
{
board = GetComponent<Board>();
}
public void ProcessInput(Vector3 inputPosition, GameObject selectedObject, Action onClick)
{
if (MoveDone)
{
board.OnSquareSelected(inputPosition);
}
}
public void SetMoveDone(bool value)
{
MoveDone = value;
}
}```
oh the GetComponent
I got a problem with MultiplayerInput with this codes
first of all networking questions go in #archived-networking
also dont crosspost
okay thanks