#💻┃code-beginner
1 messages · Page 340 of 1
ohh that might be it
seems thats what it was, I put the check in for the if, but forgot about the else if
ive tinkered with it and now it doesnt immediately start hitting the player but it also never hits the player because it only detects the player's viewsphere which ive set to invisible tag and it only hits if the tag is player
weird that it was only spawning 2 though since rnd can go up to 3
but maybe i just got unlucky and didnt get to see it with rnd 3
Does the view sphere have an rb?
no but its parent does
Then it's gonna use the layer of the parent
so i cant make it only detect the player body?
or maybe i add a kinematic rb to the viewsphere?
Every individual collider needs it's own rigidbody. Otherwise it would be part of a compound collider.
ic
I wasn't aware that the layer of the rigidbody would clobber the layer of the collider's object
a little question why when i Instantiate(prefab,new Vector2(i,4.4f),quaternion.RotateZ(190)); that rotate only at 86.198 ?
That will return a quaternion that represents an orientation of something rotated 190 degrees about the Z axis. There are infinitely many ways to express that with euler angles. It's possible that the X or Y values are also changed to achieve the same orientation. Try to change the object's rotation in the inspector to 0,0,190 and see if it is physically in a different orientation
the rotation of the prefab?
The thing that's instantiated.
Pause the game, change the rotation, and see if it's actually at an incorrect angle
or if it's just being displayed as some value you aren't expecting
ok ty
so i added the rb but it still only detects the collider
Could you tell the issue so that I can try to help you out?
well basically i have an enemy class that has an attacksphere where if the player is in that area itll trigger ontriggerstay and damage the player
but the player has a viewsphere called collider where if the enemy is in it itll change material and that collider keeps colliding with the attacksphere and then the playerbody doesnt show up
https://gdl.space/wokeziyiya.cpp this is the attacksphere code
it checks for player but it encounters collider before the playerbody and collider doesnt have the player tag
It sounds pretty confusing to me
Why don't you just put the different colliders on different layers and use layer-based collision to filter things out?
Or have the specific colliders ignore each other?
i tried doing both of these
set the spheres to the same level and removed the collisions between the level and itself
and went into the collider and excluded the layer it was on
So, you have a Collider AttackSphere on your enemy and a Collider Viewsphere on your player, but your player also has its own Collider. The issue is that the AttackSphere doesn't ignore the Viewsphere, right?
yeah
Well, you may do what PraetorBlue said or simply check for the collider being the collider you need in your enemy's logic
By either checking the Components or tags
How have you done this?
You should make AttackSphere ignore Viewsphere, if I understand the issue correctly
Enemy doesn't seem to ignore any collisions
Oh, right, it has Collider layer
The Colliders do ignore each other
Does the 2nd image, called Collider, correspond to the Viewsphere you have mentioned?
They should ignore each other, don't they?
doesnt seem to be the case
Is it the Enemy's code?
And send the code, please
its here
Also consider answering the question
Hello.
its the code of attacksphere which is in enemy if thats what you mean
I'm the latest newbie off the bus
Is the script attached to the AttackSphere?
yes
I have 30+ years programming experience
But Unity is new
So I'm a rookie
And I have a key question
Please, consider asking your question in a single message for it not to be interfered.
I get scripting, declaring variables in a .cs file and making connections and operations in code. And I get visual interfaces, adding elements and auto-building code with automatic methods etc. But I'm stuck on something weird
Could you print the layers of both GameObjects?
collision.gameObject.layer
okay
Then send a screenshot
Sorry cashiering at the same time x.x
ok, so you have 30+ years programming in what language?
Damn times are rough out there if a 30+ year programmer needs to be a cashier too 😦
Disregarding tbat
slasher
private void OnTriggerEnter(Collider other) {
Debug.Log(sphere.gameObject.name + " layer: " + sphere.gameObject.layer + "\n" + other.gameObject.name + " layer: " + other.gameObject.layer);
if (other.CompareTag("Player")) {
canHit = true;
}
}```
You make variables in a .cs, attach it as a component, then link the data to other components in the visual inferface.
WTF?
How can you tell from the script what is attached to what?
From the script? The script only defines a blueprint for a component.
You can see the actual component in the inspector when you attach it to an object. In the inspector, you can see what is assigned to it.
good to know
The components on objects would be instances.
Yeah, can be done with
$"variable: {variable};\nvariable2: {variable2}"
Ah. Gimme a second to consider that
Right, so the objects collide, apparently, even though the collision between them is disabled.
yeah idk why
You'll not have access to the hierarchy objects directly without proper referencing or Finding the objects in the scene and will mainly be working with callback methods.
Could you show the layers one more time?
Also, do you have a 2D or 3D game?
When you attach a script to an object, you're making an instance of that class attached to that specific object. Then you can drag in other references for that instance
3d
Are you sure you're configuring the matrix you need?
So in Physics, not Physics 2D
I meant the collision matrix in Project Settings -> Physics -> Layer Collision Matrix
And both objects are Colliders..
yeah
And the collision is disabled..
Actually
Why do they exclude layers?
On your SphereCollider
Exclude Layers: Collider
i added that when fooling around im testing it again excluding no layers
Debug.Log($"A collision occurred between {name} and {other.name}");
Debug.Log($"Click this message to have {name} highlighted in the hierarchy", this);
Debug.Log($"Click this message to have {other.name} highlighted in the hierarchy", other);```
still collided
So the BattleHandler.cs is a code module blueprint,
These objects don't match your log. Your log says ViewSphere and AttackSphere are colliding
doesn't look like "Collider" is colliding
which is as expected
And the attached component is an instance of that blueprint
Correct?
yes
Thanksm
really the "class" inside the script is the blueprint for the component
public class BattleHandler
viewsphere is the viewsphere of the enemy and collider is the viewsphere of the player, and collider is at the end of the log
Clicking on the logs, do they highlight the correct objects? @gentle stratus
didnt seem to actually highlight
when i doubleclick it just goes to the attacksphere code
I'm assuming you've got other objects with attack spheres and view spheres besides those shown - or on both enemy and players without the correct layers.
I've edited the message
ok
In that case hardcoding a connection in the script is.. slightly less clean? Than connecting vis the interface?
it highlights the collider and the whole enemy prefab
Prefab? You mean the enemy object in the scene?
yeah
But I'm never gonna have two battlehandler instances. Is there a better way to do this than a comonent connection?
nvm thought yu were talking about web lol
Meaning the rigid body was on the enemy that had a different layer (not collider) and not the part of the enemy with said collider and correct layer.
Does anyone know how to fix this decal stretching issue? this is for bullet holes applied to corners:
and relevent code:
{
// Define an offset distance to move the decal into the wall
float offsetDistance = 0.2f; // Adjust this value as needed
// Calculate the position of the decal slightly deeper into the wall
Vector3 spawnPos = hit.point - hit.normal * offsetDistance;
// Instantiate the bullet hole object at the calculated position
GameObject spawnedObject = Instantiate(bulletHolePrefab, spawnPos, Quaternion.identity);
// Align the bullet hole with the hit normal (assuming your bullet hole prefab is facing in the positive Z direction)
spawnedObject.transform.forward = hit.normal;
// Optionally, you can parent the bullet hole to a container
spawnedObject.transform.SetParent(bulletHoleContainer.transform);
}```
are you talking about references ?
think i see the issue now, the enemy object itself also has attack detection
cause i needed to link it with my animator
most likely because you're setting the bullet hole as a child of something that is scaled
spawnedObject.transform.SetParent(bulletHoleContainer.transform);
Oh sorry actually - I just looked at the screenshot. You're using a decal projector. Projector is going to wrap around the thing it's being projected on.
nvm even when i turned it off it still collides with collider
Commenting that out causes the same issues, so with no parent for each bullet hole the issue is the same
you can try making the Depth smaller so it doesn't go so far in the mesh
if you don't want it to have stretch on the object it's projecting on, you should just use a Quad mesh, not a projector
where could i find the option to create a quad mesh?
It's one of the standard primitives in unity.
If BattleHandler.cs is attached to a GameObject as a Component, I get an instance of code I'll only ever use one time. Is there a betyer way?
Right click, create 3D object, Quad.
so you're saying that the decal projector can't handle corners?
Create a Singleton manager that'd have a reference to your necessary battle handler if you want pseudo global access to the object.
Use it one time for what and where? I'm assuming you're wanting access to it in some other class.
with the right rotation it seems more than possible but im unsure of the math behind calculating this
To get this you'd have to just sample the surface normal at a few points
and maybe take the average
i'll have to look into this, thank you
why the hell this error pop in my console (that dont affect my game) ```NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <4fa92967e90043cbb25cde5b275e9e4e>:0)
because it was some type of editor window /tab /item took a dump somewhere, you can clear n move on
generally UnityEditor errors are not caused by you directly
How does this differ from a GameObject in the interface? I've only ever made GameObjects.
Or, does the manager also attach to a GameObject?
it attaches to a GameObject
Singleton pattern with Unity objects would consist of your standard Game Object but with the usual public static Instance member and the single constraint test in Awake.
Okay. Thanks.
Truth be told, I was handed someone else's code [In Unity?!] And was told: "this doesn't work. Fix it"
I've been doing my best for a few weeks now. Thanks for the backup
ok ty
It's still not fixed, is it?
nop
I'll return if/when I have more questions.
Alright, show me the current objects one more time
Which are supposed to collide
Not supposed, actually
And print the objects using the Debug.Log's 2nd parameter, Object context
yeah i added this from delphat's suggestion
private void OnTriggerEnter(Collider other) {
if (other.transform.parent.CompareTag("Enemy")) return;
Debug.Log($"A collision occurred between {name} and {other.name}");
Debug.Log($"Click this message to have {name} highlighted in the hierarchy", this);
Debug.Log($"Click this message to have {other.name} highlighted in the hierarchy", other);
if (other.CompareTag("Player")) {
canHit = true;
}
}```
how can i check what is setting a script active to false? i havent written any code and have no references to this code whatsoever and something is setting it to false and i have no diea why
Awake can sometimes automatically disable a script if it has a NRE
this only happens after awake should be called
i'll send a video
the outline disables itself and idk why
after you come back
add OnDisable and put a breakpoint in it
from the frozen
strange, logging something shows theres a method in the player where it disables the outline, but it doesnt say what is calling that method
show the stack trace
left one is from the outline script
and right one is from disableoutline on the character
share the Character script.
its almost 1000 lines long are you sure
yes, I won't die
i'll paste it in a thingy one sec
https://gdl.space/xoduyiyuro.cs
might be a bit messy 😅
i've tried to keep it as tidy as possible
i found the culprit 😭
-
- Are these the objects that are not supposed to collide?
-
- Have you check it out properly?
-
- Are you absolutely sure?
ah, an animation event
i'm surprised there wasn't at least a hint as to where that came from
doesn't it use reflection?
indeed, but I'd still expect to see the code responsible for doing that reflection
maybe that's all native
isn't it basically the same as GameObject.SendMessage ?
messages are also reflection-based
can you access a custom tilemap rule tile's properties from a raycast?
if you know the class you need, use the WorldToCell and then GetTile
You've got an invalid cast exception
Should probably check what type of tile you're grabbing first
btw this has a generic version with <T>
Yeah I just don't know how to make it valid. GameRuleTile inherits from RuleTile so it should work...
The get tile?
Well, Get Tile returns a Tile Base
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.GetTile.html
Oh I didn't know you had to specify the type with the <> it doesn't return an error anymore
Thanks!
can you change a variables access modifier at runtime?
no. why would you?
i was just wondering if u could lmao
well just like how you cannot change the actual lines of code at runtime (because they've already been compiled into IL), you cannot change the access modifier for a variable or any other object
Literally what would that even do
Is there a way to change the color of a rule tile in runtime? I've currently got it like this with another script calling changecolor during runtime but it doesn't actually change anything until I exit playmode.
TileData myTileData;
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
base.GetTileData(position, tilemap, ref tileData);
tileData.color = color;
tileData.flags = TileFlags.LockColor;
myTileData = tileData;
}
public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject instantiatedGameObject)
{
color = Color.white;
myTileData.color = color;
myTileData.flags = TileFlags.LockColor;
return base.StartUp(position, tilemap, instantiatedGameObject);
}
public void ChangeColor()
{
myTileData.color = color;
myTileData.flags = TileFlags.LockColor;
}```
I should clarify that the color variable changes but it just doesn't actually affect the sprite
try removing the lockcolor flag before assigning the color
idk LOL
Nah that didn't work
is someone kind enough to show me how would jumping look like in a fps controller script? I'm currently using Move and it looks like teleporting
if (Input.GetKey(jumpKey))
{
Debug.Log("Jumping");
if (isGrounded)
{
controller.Move(Vector3.up * Mathf.Sqrt(jumpHeight * 2f * gravity));
isJumping = true;
}
}
or just use the premade controllers from starter asset
How do you create adaptive joystick on touch screen?
Don't worry about it
If you're posting in #💻┃code-beginner you should basically pretend literally any C# code containing the word "unsafe" just does not exist
i personally just use AddForce as an impulse
If you mean for the above jump issue, you can't use AddForce on a CharacterController
oh didnt notice that part
Jumping is killing me 😭
.Move is an amount to move this frame. If you want to jump you will need to track velocity over several frames, and use that velocity to call .Move
You'd increase the Y velocity by some amount, and then decrease that every frame until you're back on the ground
for(int index = 0; index < unitCount; index++)
{
//add unit to list as prefab
units.Add(Instantiate(prefab) as GameObject);
// lock origin to Formation position
units[index].transform.SetParent(gameObject.transform);
//reset position to equal formation position;
units[index].transform.position = gameObject.transform.position;
//set desired position
units[index].transform.position = new Vector3(0 + 5 * index, 0, 0); // ???
}
When I use the new Vector 3 to set a new position for the 'Unit' game object, 0 is not based on the position of the parent game object. I thought that by setting the parent I'm changing what 0 is for the child?
You are using transform.position which is in world space.
if you want local position use transform.localPosition
Maybe you want to set the local position, setting the position itself will move the object to that position
Is there any reason that this wouldn't be changing a rule tile's color in runtime? I can't find anything helpful online.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
TileData is a struct. Changing your tile data struct won't affect wherever you copied it from.
!docs
Structs are value types
I checked the unity learn for rule tiles and the rule tile documentation neither was helpful
So is there no possible way to change the color values during runtime then?
Because it works when it's in the editor
If you want to change a tile color at runtime you would use https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetColor.html
You would need to set the tile's tileData to the new one you've made. Or pass it as a ref to ChangeColor
Or yeah, use that. I don't really work with tiles so I didn't know there was a function for it
or this.color = whatever;
I'm trying to change the color for rule all the rule tiles of a specific type within a tilemap not the whole tile map or an individual tile
Try this
Ok I'll try that
Thanks, that was a problem. I noticed that you can overload the Instantiate function, something like units.Add(Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject);. Is it possible to use this overload to set a local position or is that argument always going to set the global position?
it is always world space position
alright ty
this form of Instantiate doesn't create it under a parent anyway
so local position wouldn't mattter
Also you don't need as GameObject if the prefab variable is of type GameObject
How do I use quality modes in ui like high low is there API for that?
CustomAnimation customAnim;
void Start()
{
customAnim = GetComponent<CustomAnimation>();
}
void StopGrapple()
{
customAnim.whenKeyPressed(true);
}
why do i get the error "NullReferenceException: Object reference not set to an instance of an object" when stop grapple is played?
Because customAnim is null
Does this object have a CustomAnimation component on it?
no, one its parents do tho
customAnim must be null, logically
So that would be why it's null
because there isn't one
Well GetComponent doesn't care much about "one of its parents"
so I find the parent and then do get component?
Maybe you want GetComponentInParent?
Or just make the field public and drag it in
yah i will try that
There doesn't seem to be any function for setting the tile data. I tried this but it didn't work. I'm not sure if there's something about what you were suggesting that I'm missing... I'm sorry I'm pretty inexperienced...
Shouldn't you be setting color?
Why are you reading color
color is just a public variable that I created it isn't connected to anything
Pretty sure what you want is someting like this:
public void ChangeColor(Vector3Int tilePos) {
this.color = myITilemap.GetColor(tilePos);
}```
Is this class derived from Tile?
It's derived from RuleTile
Then you maybe want:
public void ChangeColor(Vector3Int tilePos) {
base.color = this.color;
}```
You shouldn't mask field names from the base class ideally
Oh I see TileBase doesn't have a color
well I guess I don't understand how you're using this color variable then
like I said the color variable is just a public one I created and named color
The other scripts change the color variable then call ChangeColor
The tutorial I followed that was explaining rule tiles showed that you could make a public color variable, then set the tiledata to that color in gettiledata. So I've been trying to work off of that.
The tile may have its color locked.
why is that a thing? i do not know!
let me find where that is..
I have always just used tilemap.SetColor(theCell, theColor);
ah, I see: you want to change them all
let me check something..
yeah, so the problem is that it just copies the data from your Tile asset. Changing the asset after setting the tile doesn't do anything.
I just tried doing that in a 2D project. Existing tiles didn't change.
New uses of the tile do use the new color, of course.
Oh I see. That's too bad. Guess I'll have to find another solution.
If the tilemap is small, iterate over the entire tilemap and just set colors as needed
If it's large, I'd make a hash set of Vector3Int that you populate with the positions of the tiles you want to change
I have some problems with UI image in unity can someone help me with it?
you need to say what problems you have
My UI image suddenly turns into script idk how to fix it
what does that even mean? show a video maybe or try explaining better?
https://www.youtube.com/watch?v=yxzg8jswZ8A&list=PLgOEwFbvGm5o8hayFB6skAfa8Z-mw4dPV&index=7
[7:26] when I try to duplicate my image UI it suddenly turns into a script which does not happen here
In this episode we'll create a health system. We will add health to our player, create a health bar, make a deadly saw trap that can damage the player and health collectibles to restore your health.
➤ Download the heart sprites: https://drive.google.com/drive/folders/1audm9sjm-JiGRu4PtckMoI8a_nudnzHg?usp=sharing
➤ Starting Project: https://gith...
turns into a script how?
what does that mean
If i create any type of UI Slider and press play it turns invisible and all children "Images" become "Scripts". This happends even if i dont use it for anything.
screenshot it
I'll try it thanks
I got this error after re-opens the unity
Error loading the file 'VirtualArtifacts/Primary/13bd0b2b84cd782408ba37c684c50988'. File is either empty or corrupted, please verify the file contents.
What the forums suggests
https://forum.unity.com/threads/how-do-i-remove-a-virtualartifact-thats-been-corrupted.1337042/
I was able to Instantiate as child and shorten my code over all with units.Add(Instantiate(prefab, this.transform));
one thing I'm trying to do is that when the player touches the Muon gameobject, the UI Image should switches to a face of the muon instead of being completely black, But instead when i touches the muon gameobject, the UI Image doesn't switch
https://gdl.space/exowoqaneh.cpp
like similar to when Mario collect giant coins
Is this code running? Verify that first.
should I Debug?
That would be one way to verify it
And before you show some random code with a "like this?" Comment, please actually test it.
the debug doesn't seem to trigger
Check this prior to the switch statementcs Debug.Log($"The tag was: {muonTag}");
it doesn't seem to trigger the debug either
I tried the first and the second one but doesn't call the Debug
then that method is not being called
If this one doesn't print the debug then you are never running this function
where are you calling it from
https://gdl.space/voseqiyolu.cs well it supposed to function when the Muon gameobject get touched and triggers and the UI Image changes to the face of the rescued muon
okay but where are you calling it from
SetMuonRescued method should be called from the script or component that handles the player's interaction with the Muon GameObjects
okay so make sure that code is running
but how?
The same way you just determined this one was not
You'll need to show us the script or component that handles the player's interaction - the one that supposedly calls this function.
So, you remember how you just logged something before a conditional statement to see if it was occurring?
Do that, again, but here
log the thing you're checking for and see if it's actually true
well I did try to Debug.log it but when i playtested and touches the gameobject, no debug.log appears in the console
Then that function isn't being run
Did you click on the object? OnMouseDown only occurs when the mouse button is down/clicked whilst over the target - the target requires a collider.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
the muon gameobjects have a collider
Did you click on them in the scene?
where did you put the log
there's also another huge logic issue here. you specifically check if the object you clicked on has the tag Muon then you pass it to your SetMuonRescued method which checks for different tags. so even once you get the code actually running, your logic is going to prevent it from working the way you expect it to
well no, I walked into them as the player
and what about the function name OnMouseDown made you think walking into them had fucking anything to do with it
OnMouseDownonly occurs when the mouse button is down/clicked whilst over the target
Maybe you're wanting on trigger enter
Though this would imply that you're using Rigidbody physics
Before we continue, I really, really want to know why you thought OnMouseDown was called when the player walked into it
should i use
sbyte[] sbyteArray = ArrayPool<sbyte>.Shared.Rent(5);
or normal arrays?
I did searched up on google about interaction and see this, I didn't know OnMouseDown on void would have any meaning (since I only know that a lot of the things next to void are just having names to know what it is, except for start and awake)
What's the context and what do you mean by normal array? Are you referring to the type sbyte?
If the name doesn't mean anything, then it would literally never be running unless you specifically called it. So, if you assumed OnMouseDown was a name, where did you try to call it in your own code?
yeah i mean should i do sbyte[] {1,2,3} or rent from the pool and stuff?
trying to call MuonUIController with the SetMuonRescued to tell the UI Image changes to different image base don what Muon you have Rescued
(I didn't know other names have meanings, I only know Start and Awake have meanings)
Are you running into performance issues related to memory allocation for arrays?
Im getting a "Type or namespace TextMeshProUGUI could not be found error but it was working moments ago in this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Dialogue : MonoBehaviour
{
[SerializeField]
private TextMeshProUGUI textComponent;
Any idea what couldve caused this
So, either you thought it was a Unity function that Unity would call, or you thought it was a custom function that has to be called manually. I'll accept you didn't know it was a Unity function, so show where you were trying to call it manually
They're primitive value types. I don't see why you'd need to pool them.
do you see this error only in your IDE or do you see it in the unity console as well?
I only see the error in the unity console
And because of this i cant set the reference in the serializefield
well that sounds like you either need to save your code again or your need to get your !IDE configured or both
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
You'll want to configure your ide. It's highly advised and necessary to get help on this discord server with regards to code questions #854851968446365696
I am trying to call SetMuonRescued
public void SetMuonRescued(GameObject muonGameObject)
{
string muonTag = muonGameObject.tag;
Image muonImage = null;
switch (muonTag)
{
case "Muon1":
if (!muon1Rescued)
{
muon1Rescued = true;
muonImage = muon1Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
case "Muon2":
if (!muon2Rescued)
{
muon2Rescued = true;
muonImage = muon2Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
case "Muon3":
if (!muon3Rescued)
{
muon3Rescued = true;
muonImage = muon3Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
}
if (muonImage != null)
{
muonImage.sprite = rescuedSprite;
}
}
Okay, and where are you calling that function?
in MuonUIController script
Im using Visual studio and it seems to be updated already
Where in MuonUIController
https://gdl.space/pamenasome.cs in here
This is the same thing you just showed me
So where are you calling SetMuonRescued
https://gdl.space/jeleneyuki.cpp in here
public class OuumaNPC : MonoBehaviour
{
[SerializeField]
private MovementScript movementScript;
```Is this the right way to reference a script?
Okay, and as we established, you did not know OnMouseDown was a Unity function that would be automatically called, correct?
yeah
So, where did you try to call OnMouseDown
You'll want to go through the installation guides again. You won't need to uninstall/reinstall but rather just run the installer. It'll allow you to modify your current installation. Most often, folks miss the workloads step (3) that has it's image shown below step 5 https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#install-visual-studio-and-unity
I don't know where, it's the only script that have that OnMouseDown
So then we remain with the same question. Why did you think walking your character into this would call OnMouseDown
OnMouseDown doesn't do what you think it does.
Yes but even assuming that, I still want to know where this idea came from
This function will not be called unless you click on the Muno in the scene, which isn't what you're wanting to do.
Likely random copied code
They ought to really follow a tutorial instead of walking into this blindly
I know that but I'm continuing in my several-day journey to try to explain to them that reading the code explains the code
I have this installed already, dint miss that step
I just didn't know it was unity function, the only unity functions I know is awake and start, OnColliderEnter2D, OnColliderExit2D, etc
I know that. I don't care, I am willing to accept that you did not know. That does not change my question
Check your external tools in the Unity Editor and make sure it's correct (yours will show your version)
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#install-visual-studio-and-unity
Since you didn't know Unity would call it, that would mean that you tried to call it
so where
did you
try
either you thought "This is a Unity function" and it ran when something happened. Or you thought "This is not a Unity function" which would mean you intended to call it manually
The function won't automatically run if you don't call it or if it isn't a built-in callback function (message)
So either:
- Where and when did you try calling it
- Did you assume code is magic and it would just psychically know you wanted that function called at that point
Only the functions from the Messages section are automatically called, given the correct conditions.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
Code means things. It can be understood. You have to stop assuming it's brain-scanning wizardry that can read your intentions as you type the Sacred Keystrokes™️ into the machine and that only The Ancient Ones can communicate with the Machine
For example, when I ask you "What do you think this line does" and your answer is "I don't remember it was a while since I wrote it" that's telling that you don't think code can be understood unless you were there when it was written. It's literally just words. It conveys meaning exactly as precise and discernable as my text on your screen right now.
Glyphs that translate into tangible thought. It does not matter whether the font is serif of monospace it's still language
You may need to regenerate your project and restart the Unity Editor if all of the above have been completed but still doesn't work (Intellisense). @paper peak
It's absolutely necessary to acquire help from this Discord server though as these are syntactical mistakes that really ought to be immediately addressed by Intellisense - you'll know it's incorrect the moment you try to type it (it would not even be an available option) or better yet, be given the appropriate correct suggestion.
Should i be worried about this warning?
I restarted both Visual studio and unity, visual studio seems to be working better with c# so it seems to have fixed itself but now im getting this warning
you closed project with compile error?
If you currently have compile errors, it can't be sure the editor scripts aren't to blame. Safe mode would disable all editor scripts so you can get in and fix them. You can hit ignore to go in, but your project won't run until you fix the errors
I was busy doing something, is this better?
public MuonUIController muonUIController;
private void OnCollisionEnter2D(Collision2D collision)
{
string muonTag = collision.gameObject.tag;
// Check if the collision is with a Muon GameObject
if (muonTag == "Muon1" || muonTag == "Muon2" || muonTag == "Muon3")
{
// Call the SetMuonRescued method on the MuonUIController
muonUIController.SetMuonRescued(collision.gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OuumaNPC : MonoBehaviour
{
[SerializeField]
private MovementScript movementScript;
```Last line seems to be giving the error, is this the right way to reference a script?
What is the error
Type or namespace MovementScript could not be found
What is MovementScript
Its a script im trying to reference, it is stored in the same folder this script is in
Show it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private Animator animator;
public bool canMove = true;
private float horizontal;
[SerializeField]
private float maxSpeed = 4f;
private float currentSpeed = 0f;
[SerializeField]
private float jumpPower = 12f;
[SerializeField]
private float timeToZero = .15f;
float deaccelerationRate;
private bool isFacingRight = true;
```Everything below is just methods
No, show MovementScript
This would only occur on a collision event between solid objects. I'm assuming your objects aren't solid though as they're trigger types.
I dont get it, this is the script
Do they need to have the same name to be referenced?
No, this is PlayerMovement. Show MovementScript
That would be the correct way how to reference a script called MovementScript.
How else would the code know which type you wanted
I'm assuming there isn't such a thing which either implies your ide isn't configured or these were code before your configuration.
So i got confused on how it works here
Also the other error about TextMeshProUGUI got fixed, seems like you were right and IDE wasnt properly configured
Thanks for the help
since I am using the collider2D which triggers..
private void OnTriggerEnter2D(Collider2D other)
{
string muonTag = other.gameObject.tag;
// Check if the trigger is with a Muon GameObject
if (muonTag == "Muon1" || muonTag == "Muon2" || muonTag == "Muon3")
{
// Call the SetMuonRescued method on the MuonUIController
muonUIController.SetMuonRescued(other.gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MuonInteraction : MonoBehaviour
{
public MuonUIController muonUIController;
private void OnTriggerEnter2D(Collider2D other)
{
string muonTag = other.gameObject.tag;
Debug.Log("Trigger entered with tag: " + muonTag);
// Check if the trigger is with a Muon GameObject
if (muonTag == "Muon1" || muonTag == "Muon2" || muonTag == "Muon3")
{
Debug.Log("Muon rescued: " + muonTag);
// Call the SetMuonRescued method on the MuonUIController
muonUIController.SetMuonRescued(other.gameObject);
}
}
}
well it seems functional but the UI Image still doesn't change
Good job debugging thus far. So the script stated that player hit this object.
Okay, so you can see the tags that interacted with this. Now tell me, what is your code supposed to do when the thing it collides with is tagged Untagged or Player?
is supposed to be tag Muon1, Muon2 and Muon3
which are the three gameobjects on
But right now the thing interacting with this object is tagged Untagged, or Player
You can see that
This object never collides with anything tagged Muon1, Muon2, or Muon3
You'll either want to have this script on the other object (the player) OR check/use this object's tag instead after evaluating if Player had hit this object (assuming this component was placed on a Muon)
the 3 main objects have the 3 tag names
Then none of these objects are colliding with the object that has this script on it
the 3 objects have the interaction script on each though
Doesn't change the fact that nothing tagged Muon1, Muon2, or Muon3 is colliding with any object that has this script on it
They're the Muon. What had hit them isn't a Muon.
that is strange
Why is it strange? Where is a Muon colliding with an object that has this script on it?
The OnTriggerEnter2d message is from the perspective of who got hit. The script is on the Muon object so other would have a tag of "Player" and not "MuonX"
so, i am supposed to put it on the player?
Hey! For some reason my shaderGraph effects arent rendering in the game, but it is in the scene. Is there anything I should be looking for to fix this??
Try it and see
You're supposed to think a bit. Which object do you want to be doing a thing, and when do you want that thing to be happening
This is the beginner coding channel. You'll probably get more appropriate support in #archived-shaders or #💻┃unity-talk
when i tried it, it's debugging ground2 for some reason, and when I touched the gameobject, the animations aren'ts working anymore
The logs are correct so at the very least you know the code is flowing correctly.
The reason it's logging ground2 is because you're colliding with something tagged ground2
you're logging the tag of the thing that this object collides with
oh
yeah, but the animations for the muon when it gets rescued aren't working anymore (or the script of the muons)
So, what plays the animations
another script called MuonController
any errors?
So, put to use the skills you've just learned. You know how to call functions, and you know how to debug log. Find out what's calling it and why it isn't playing
Maybe show your current SetMuonRescue code
not really a code question but when i build and run my project some sprites dont export with the project (at least thats what it looks like)
ik i can check the folders path when exporting and see if its correct but i dont know how to get to there
don't send "not really a code question" in a coding channel?
#🔎┃find-a-channel
public void SetMuonRescued(GameObject muonGameObject)
{
string muonTag = muonGameObject.tag;
Image muonImage = null;
switch (muonTag)
{
case "Muon1":
if (!muon1Rescued)
{
muon1Rescued = true;
muonImage = muon1Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
case "Muon2":
if (!muon2Rescued)
{
muon2Rescued = true;
muonImage = muon2Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
case "Muon3":
if (!muon3Rescued)
{
muon3Rescued = true;
muonImage = muon3Image;
muonGameObject.GetComponent<Collider2D>().enabled = false;
}
break;
}
if (muonImage != null)
{
muonImage.sprite = rescuedSprite;
}
}
probably better to use a code pasting site for code this big
ye mb
Log muonTag before the switch. See what tag it gets
Okay looks like it's running just fine.
yeah, and for some reasuon MuonController script in the Muon gameobjects are not working
What are you expecting to happen that isn't happening
like when you interact with the gameobject, it does the rescue animation and the the happy animation when he's rescued. https://gdl.space/ireketekux.cs
This is a completely new script. When did we start talking about this one?
this is for the Muon Gameobjects to do the animations when the player collides with them. I just wondering because this script doesn't owrk anymore after putting the MuonInteraction on the player object
So, this is a completely new on trigger function. You know how to log the object this collided with to see what tag it has
try that
Instead of just logging text, why not log the thing you check in the if statement right after
Hello! I think I have a simple question - I'm trying to do a raycast from an object to an area in front of the object (to see if there's any colliders there) so I tried using this.transform.forward (the object's transform direction)
but when I rotate the object the raycast remains fixed in one spot (doesn't change depending on where the object is facing)
is there a different vector I should be using to get the forward direction?
Instead of just logging text, why not log the thing you check in the if statement right after
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("OnTriggerEnter2D");
if (collision.CompareTag("Player") || CompareTag("Player 2") && !isRescued)
{
Debug.Log("muon collision");
isRescued = true;
animator.SetTrigger("Rescued");
animator.SetBool("isRescued", true);
popSound.Play();
// Start a coroutine to handle the happy animation and disappearance
StartCoroutine(HappyAnimationAndDisappear());
}
}
it do debug OnTriggerEnter2D but not muon collision
Instead of just logging text, why not log the thing you check in the if statement right after
Hi i have a question with a simple mechanic i am trying to develop, it is a system where you are using a shopping cart and i need the shopping cart to lag behind the player's movements. I got the rotation working but the movement is tricky since the cart is parented to the player. I have the cart working where it will move to the player's position with the lag, but in only one direction
if you use a smoothdamp or lerp or something with an offset on the player's transform.forward it should work in any axis
what do you mean by log the thing?
I might unparent it to prevent other issues too but if you can get it to work while parented go for it
the thing you're checking linedol
if you're trying to figure out why x isn't y, log x and not some random string
Thanks, ill try to see what i can do
wrong reply?
lmk if you have any other questions tho
oh, mb
Instead of just logging text, why not log the thing you check in the if statement right after
what am I suppesed to write?
Instead of just logging text, why not log the thing you check in the if statement right after
that doesn't explain anything
😭
which part of that sentence do you not understand
if your goal is to figure out why something isn't working
figure out what is happening that isn't what you expect
and then make it what you expect
"why not log the thing you check in the if statement right after" like what am i supposed to write there?
... a debug.log of the thing you're checking
Please tell me what part of that sentence you do not understand
that instead of text, log the thing i check in the statement right after, like what is it I'm supposed to write, like this?
that's certainly a start
Hey see what you can accomplish whenever you actually think
Instead of just waiting for someone to write it for you
🤯
when i did that and tried, nothing debugs like if (collision.CompareTag("Player") || CompareTag("Player 2") && !isRescued) is not functionaly
you have to put it outside the if statement
If nothing logged, then that line is never reached
@hushed hinge Make another thread please, stop taking over these channels.
I'm not spending another fucking 11 hours explaining debug logs this time I'm gonna go play Hades
take a well deserved break 💀
muon animation
I can't get the character to dash, for some reason velocity is being changed but i see no movement
(dashes with c key)
Well you're overwriting the velocity each frame
_rigidBody2D.velocity = new Vector2(_currentSpeed,_rigidBody2D.velocity.y);
ah fuck you're right 💀
Idk for sure if this is the right channel but does anyone know why this distortion is happening
Ping if respond ples
how can i disable the 60 fps cap in editor?
there's a checkbox for vsync in the aspect ratio selector for the game view. also not a code question
my circlecollider2D and polygoncollider2D are not detecting collisions, any idea what the issue might be?
the object with the polygoncollider2D is a prefab that gets instantiated at runtime, just fyi incase that matters
I did what it says on there already
then show the other rigidbody2d involved in the collision
there is no other rigidbody2D
then you did not do what it says on there already
a kinematic Rigidbody2D will only produce an OnCollisionEnter2D message when it comes into contact with a non-kinematic Rigidbody2D
oh I see
but in general you only need 1 rigidbody right?
for collisions
look at the collision matrix and find out
its stuck on building gradle project
not a code issue. #📱┃mobile for build issues for mobile devices
im on pc
okay but you are building for a mobile device, yes?
nope im building for vr
pc vr or a mobile device
How to ignore clicks?
ignore them in what capacity?
not allow player to press mouse buttons
¯_(ツ)_/¯
that's not very descriptive. but the obvious answer is to just . . . not do anything in response to those button clicks
If you just want to block the mouse input at some point you can play with the Event System. Check this video,it is a bit old but very clarifying: https://youtu.be/EVZiv7DLU6E?si=w9j1KmS_tzBOFzZx
Its kind of annoying how clicks on UI elements interact with the game world right? And the documentation is kind of sketchy on how to fix this.
Here are three sure fire ways to block clicks on UI elements. I recommend watching the whole video, and choosing the one that suits your project best.
Feel free to ask questions in the comments...
is the "beginner scripting" course on unitylearn a good starting point to learn scripting?
Hi peps, how do you download a package from github?

Say this one for example. https://github.com/azixMcAze/Unity-SerializableDictionary
that one is not set up to be a proper package that you can import using the package manager. you just need to download and import the unitypackage file from the releases
but this is how you would do it for a proper package hosted via git: https://docs.unity3d.com/Manual/upm-ui-giturl.html
hello why this line dont work ??? ``` target = GameObject.FindGameObjectsWithTag("player").transform;
target is `` public Transform target;``
can someone please take a look and tell me how can i make so i dont freeze while jumping 🙏
https://hastebin.com/share/edesebayoq.java
An array doesn't have a transform variable
Read the error message
but its not a array
"Find Game Objects"
Right, that's why read the error messages. It should explain you everything.
What does "freeze while jumping" mean?
Do you jump and then simply "fly"?
Without gravity being applied?
when i press jump, i get lifted then gravity sets me back on the ground, i dont know how to implement a smooth jump so when i jumo while walking, i jump into that direction
First of all, in this code, the value should be added instead of being assigned
moveDirection.y += Mathf.Sqrt(jumpHeight * 2f * gravity);
The issue is that you only apply movement when grounded:
vate void UpdateMovement()
{
if (isGrounded)
{
You need to implement movement logic when not grounded.
Why would they want to use WASD movement when in the middle of the jump?
The gravity is already applied in Update method when the character is not grounded
// Apply gravity
if (!isGrounded)
{
isJumping = true;
moveDirection.y += Physics.gravity.y * Time.deltaTime;
}
oh im silly
well in an fps game you can move while jumping? you dont just move up
Actually, why do you even apply 2 gravities?
// Update
moveDirection.y += Physics.gravity.y * Time.deltaTime;
// UpdateMovement
moveDirection.y -= gravity * Time.deltaTime;
sorry im a begginer 😭
I'm not blaming you, it was a simple question
you will never outgrow mistakes like this 🙂
I still make em
Physics.gravity.y is -9.81 by default, so both gravities are applied to the bottom
they're the hardest to find as well, since your code is doing what it's supposed to
ive coded most of the code without the jump and then i copied the jump code from https://forum.unity.com/threads/rigidbody-fps-controller-jumping.1050956/ as someone suggested me yesterday from this chat. So it's quie a mess atm
Why would you copy the code from the question, which reports undesired behavior?
Well, right, but this is not what's causing the issue
Also enabling moving while still being in a jump is up to you
Have you fixed this one?
yes 😓
Does this change something?
well i cant jump as isGrounded is set to true because of gravity but if i set isGrounded to always true in UpdateMovement i can sometime jump, sometimes it doesnt seem to work
i dont have any record app but if you want i could stream you the results
It doesn't have to be wasd. It can be whatever they want. The point is to implement that logic.
The "Top Left Down Right" logic is usually referred to as WASD.
If you're using Windows, it has a built-in recording tool, which can be accessed by pressing Windows + G
Why would you set isGrounded to true, if it should just be equal to controller.isGrounded
I would say, the gravity should be applied regardless of the isGrounded boolean
// Apply gravity
if (!isGrounded)
{
isJumping = true;
moveDirection.y += Physics.gravity.y * Time.deltaTime;
}
video is too large for discord 🙂
Don't make your video longer than 30 seconds
Well, so what's the issue?
I see your character jumping perfectly, am I missing something?
You have sent the empty code
im jumping good once every two times
wth my particle dont spawn :( void OnTriggerEnter2D () { Instantiate(explosionEffect, transform.position, transform.rotation); Destroy(gameObject); }
Well, you're jumping just when the character is grounded?
that only Destroy my gameobject but not instanciate my effect
im trying to only allow to jump if charater isgrounded then remove the is grounded as it's not touching the air
isGrounded is assigned to the CharacterController.isGrounded, so it's managed by the CharacterController and you don't have to do it yourself
Anyone knows a way to visualize Physics.CheckBox(position, halfExtents, Rotation) I'm using it in code and want to check if the behaviour is correct
OnDrawGizmos ?
im a little lost here
Using Gizmos.DrawCube
thx guys
What exactly makes you lost?
i dont understand the message about isGround
explosionEffect is a ParticleSystem, right? It should be spawned correctly. You may want to print its name, position etc.
There is a probability of you simply not seeing it
yes is that i have try the question is why i dont see it :(
its a official unity asset
How do you set your isGrounded?
isGrounded = controller.isGrounded;
why are wheel collider so shit and how can I make the steering better?
its a prefab with particle system
Probably, because of your ParticleSystem not being visible. It is instantiated.
and how i make it visible
Change the ParticleSystem
You're spawning either an invisible one or the one flying away
i change it by what ?
Change how it's looking
like yk so that i dont have to extend the backround cause when i do that it stretches the image and it looks bad
like a ui element you mean?
i use the gameobject explosion from prefab of the particle asset pack from unity
actually I'm checking on a specific orientation and drawcube doesn't allow that
idrk
Camera is a GameObject. Any GameObject can be connected to the other GameObject by making them the children of the same parent. Assigning the positions via script is usually a better option though.
guess I will have to make it in gizmo
ill do this when i get home then
What do you mean by "making it in Gizmos"?
Gizmos.DrawCube, which is, obviously, used in Gizmos, doesn't allow to change the rotation of the cube drawn directly, but you may want to change the rotation of the entire Gizmos by assigning its matrix.
Matrix4x4 Gizmos.matrix has the Quaternion Matrix4x4.rotation variable
Have a look at this thread

Well, yeah, you spawn a particle, so it should, somehow, be visible
If it's not, you should, somehow, make is visible
ohh thank you
and I meant using gizmo.drawline to make an oriented cube lol
That's also an option, right
// Check if the player is grounded
isGrounded = controller.isGrounded;
// Jumping
if (Input.GetKeyDown(jumpKey) && isGrounded)
{
//moveDirection.y = jumpForce;
moveDirection.y += Mathf.Sqrt(jumpHeight * 22f * gravity);
Debug.Log("Jumping move:" + moveDirection.y + " gravity:" + gravity + " jumpHeight:" + jumpHeight + " jumpSpeed:" + jumpSpeed + " isGrounded:" + isGrounded + " jumpForce:" + jumpForce + " Time.deltaTime:" + Time.deltaTime);
}
// Apply gravity
if (!isGrounded)
{
isJumping = true;
}
moveDirection.y += Physics.gravity.y * Time.deltaTime;
// Apply vertical movement
controller.Move(moveDirection * Time.deltaTime);
i don't understand why the jump is inconsistent
bro nvm im so dumb i just dont save...
but now i have another problem xd
wth this is purple like that 😭
You haven't understood what I've been telling you before, so I have asked you about the way of you setting the isGrounded boolean. Answering the question yourself may help you to understand it.
moveDirection is just not the same all the time.
Well, these are your particles, who knows
Check the materials used
no its asset i download from unity store
Well, something's wrong with the materials
If you play the particles in the edit mode, is it the same as in the game?
Also you're supposed to apply the gravity float to your moveDirection.y
moveDirection.y -= gravity * Time.deltaTime;
You're incrementing the value in the if statement and decrementing the value later with gravity. If the increment is less than the decrement, your move direction will decrease and vise versa.
yes
ok i find with this tutorial: https://youtu.be/FnYJaiSAJV8
In this 15 second tutorial, you'll learn a quick way to get a unity pink screen fix
► Socials
Twitter: https://twitter.com/the_real_aia
Discord: https://discord.gg/EqxuvWg
My free web games: https://aiadev.fun/
► Download Unity 3D: https://on.unity.com/3cbxhXY
For more educational content on video game development, unity tutorials, and c# p...
ty
and now that looping (i disable looping option) 
oh i see
its fine now
I have a weird issue: I have a crate and a metal crate. I'd like them to be the exact same in every way (obviously different models, ignore that), except have the metal crate's checkObstacle function have a few lines changed. I have no idea how I could do that. Anything I try results in errors. Can someone tell me how to do that?
Crate Script -> https://hatebin.com/allknucvqv
Metal Crate Script -> https://hatebin.com/neqhpqkrum
You shouldn't add the same variables from the parent on the child, even if you don't see them imagine that your child class has everything the parent has. Instead of "private" you should use "protected". On the child class (MetalCrate in your case) you don't have to declare it again, just change the values or use them whatever function you want
Have you deleted the variables form MetalCrate and yous change private to protected on Crate?
I got that wrong. One sec
On MetalCrate you shouldn't have any variable, just the ones that you will use that are not in the parent
It works just how I needed it. Thanks a lot, I'll keep the protected trick in mind
||Unrelated to previous question||
This code is weirdly nested and looks ugly. I have no idea what I could do with it to keep the same functionality but reduce the ugliness. Or is this exactly how it should be written?
got rid of that unnecessary metalCrate variable
Haven't you been told not to send the screenshots of the code several times already?
One cannot even see it fully
Send just the code you want to be refactored using a site
Can you send the whole code?
!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.
it's a screenshot so you know it's exactly this triple nested if
I think that's obvious
you can send exactly this triple nested if in proper format
Yeah, but maybe we need some extra info aout of the screenshot to see what is doing and try to refactor it
didn't think about refactoring just yet honestly
Ask your question properly, without laziness, if you expect people to spend their time answering it, especially if you expect an actual helpful answer, not "yeah, go see some stuff to write code".
get rid of the nested code is refactoring
if (!encounteredWall || !hitInfo.collider.TryGetComponent(out Wall wall)) {
lastMoveDir = checkDir;
currentMoveStep = moveSteps;
return false;
}
cant you do something like this before?
to early return
early return?
this instead of the whole if chain, right?
how do i use the new input system?
See a tutorial
virtual public bool checkObstacle(Vector3 checkDir, float castSize) {
bool encounteredWall = Physics.BoxCast(transform.position + new Vector3(0f, crateSize / 2, 0f), Vector3.one * (castSize / 3f), checkDir, out RaycastHit hitInfo, Quaternion.identity, castSize);
if (!encounteredWall || !hitInfo.collider.TryGetComponent(out Wall wall)) {
lastMoveDir = checkDir;
currentMoveStep = moveSteps;
return false;
}
if (wall is Crate crate) {
if (crate is MetalCrate) { return true; }
else { return crate.checkObstacle(checkDir, castSize); }
}
else { return true; }
}
I guess it not too much better
i did but they all use different methods, whats the best way to use it?
lemme see
Well, there is no "best method"? Simply subscribe to the stuff when you need it
what do you mean by subscribe?
I would also consider the default C# naming conventions
now this happens
You'll have to read or see something about the new Input System. It uses events, which are supposed to be subscribed to
okay then
I reformated a bit how I like it
yeah i didnt change any namings
Just in case I'll send you the code to confirm if this is how you wanted it pasted -> https://hatebin.com/bldwycqsbp
This code looks much better
And I don't see any logic changed either
Ah wait
I think i see it
In my one this line
else { return crate.checkObstacle(checkDir, castSize); }
That's how it's supposed to be
it just returns
it doesnt set the
lastMoveDir = checkDir;
currentMoveStep = moveSteps;
like it did before
I see, right
my mistake
np, which bit do I change?
It only is wrong if that check returns false
But then you need another nested if again and we're back at where we started
I think this should work and is more clear. https://hatebin.com/jzcosrndbi
I think at least for now I'll keep it as it is. There might be more variants of variants I add and this can devolve into another kind of mess. Thanks for the help anyways
The logic is completely changed
I don't think so, it just needed to add a return true on default, I think it should give the same results, I just made it quickly.
The complete method: https://hatebin.com/sajbvkuqia
I would do it this way
public virtual bool CheckObstacle(Vector3 checkDir, float castSize)
{
bool encounteredWall = Physics.BoxCast(
transform.position + crateSize / 2f * Vector3.up,
castSize / 3f * Vector3.one, checkDir,
out RaycastHit hitInfo, Quaternion.identity, castSize);
if (!encounteredWall || !hitInfo.collider.TryGetComponent(out Wall wall))
{
UpdateDirection();
return false;
}
if (wall is Crate crate)
{
if (crate is MetalCrate)
return true;
bool hasObstacle = crate.checkObstacle(checkDir, castSize);
if (!hasObstacle)
UpdateDirection();
return hasObstacle;
}
return true;
void UpdateDirection()
{
lastMoveDir = checkDir;
currentMoveStep = moveSteps;
}
}
what is UpdateDirection
Added at the end
updatedirection here is really just moveObject, but I guess that's not really telligible from my end
Just rename this method how you want
This code shouldn't change your logic and is more readable, as for me
This case is never true
case MetalCrate metalCrate:
return true;
break;
MetalCrate is derived from Crate, so it's impossible for the Crate check to fail if the wall has the MetalCrate type
case Crate crate:
crate.checkObstacle(checkDir, castSize);
break;
Won't lines like these crate.checkObstacle(checkDir, castSize); make him loop to freeze anyways? Since a crate is somehow a wall, i guess to override interact?
I'm not sure what you mean. Why would this make him loop to freeze?
I see, yeah, haven't mentioned the name of the method
It should make an infinite recursion
Not sure why they're doing it though
@magic panther
yes?
Read the previous messages. You, apparantly, may have an infinite recursio
If the wall is a Crate, but not a MetalCrate
Wondering if object is serializable? I'm going to use custom editor for this.
afaik object is not serializable by Unity
it is a theoretical one
if somehow there were infinitely many crates in a row, they'd infinitely check for a wall in front of the ininite row of crates
I could put a theoretical limit of 100 crates being moved at once
If this somehow happens I messed up really bad
Any sources? I can't see anywhere that directly says this.

hello i have a question how can i make a loop for a limited time like "i want repeat that for 2 second"
Simply experience. declare a public object variable and see that it does not appear in the inspector
What are the general way people handle Characters like Player and Enemy in a RPG?
- ScriptableObjects
- Prefabs
- Using a Dictionary that holds all the info?
baseStats = new Dictionary<string, float>
{
{"Health", 100},
{"MaxHealth", 100},
{"Armor", 50},
};
- Something else entirely?
float timer=0f;
do { timer += Time.deltaTime; } while (timer <= 2f)

Wouldn't a coroutine work better?
like that ? float timer = 0f;
do { timer += Time.deltaTime; } while (timer <= 2f);
{
//my code
}
I'm thinking, isn't that synchronous?
no
where i write my code
I use prefabs
between the { and } like any other scope
before the timer += Time.deltaTime; or after
You can just make a class that has these fields defined.
@fossil tree If you do not understand the code I have written then !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
never use do while
well now is your chance to learn how to
its code beginner channel so i dont really see the problem
im in gamejam
dont really have the time
I never done game jam before ngl. 
It takes literally 5 minutes to look up and read the docs
ok ty
there are many different ways. what you have is one of them. you can define all of the stats in a separate class/struct, individual fields as part of the Player class, or as SOs (to avoid misspellings) with a dictionary
your actual player or characters can be prefabs to easily customize them. some people use a Stat class to hold and manipulate the value of the stat, or a Resource class for stats that can replenish . . .
hey so i made a game following brackeys game tutorial but now i want to add a highscore to it but i cant seem to program it correctly i need it to save when the player quits the game and display the same score again when it is rebooted
the high score resets after playing the game again
i want it to stop right as the player collides
I guess you need to look at PlayerPrefs
a second question because the thing i want make before dont work how can i make a object a parent of a other object programaticaly
gameObject.transform.SetParent(newParent.transform)
techinally yes, but all the lost children in the mall might contradict you
xddd
@fossil tree Sorry, but why are you doing a game jam if you do not know these absolute basics?
i know the basic but never use this its ok i have learn now
i make jam for learning yk
But you can easily
how to parent an object in unity. It's not that hard to search first . . .
its true sry
Generally jams are used to showcase knowledge and skill you already have, not to start learning
how do i reference a script in another script to use its funtion
a lot of people would argue otherwise, some people need a clear deadline and objective to start learning things
i not start learning its not my first game
yes
without gamejam its hard for me to find game idea and put deadline
i reset my window and now i got this error how to fix guy
An interesting concept but I would argue that a jam is a far from ideal environment to actually learn anything
try regen project files
how to do that
On this screen you should see it, ( assuming you configured all the steps before)
That's new to me. I've never heard anyone doing a game jam to learn Unity. How would you know anything helpful within such a small time frame?
I've only heard or seen people do them to test their knowledge (whether solo or with a team) or try making a prototype . . .
{
if (GameManager.instance.battleActive && !loadBattle)
{
StartCoroutine(LoadSplash());
}
}
private IEnumerator LoadSplash()
{
loadBattle = true;
Debug.Log("Calling LoadSplash");
yield return new WaitForSeconds(1);
effectInstance = Instantiate(battleSplash);
Debug.Log("calling after instantiate");
}``` my coroutine does not hit the effectInstance. before i look else where in the code. do you think its the update becuase im setting loadBattle to true
do you have timescale set to 0 ?
or does object get disabled at some point?
The coroutine is already called, so assigning loadBattle within the coroutine will not stop it from running . . .
@distant hill The OP has already stated 'He is doing the jam to learn' but also 'I'm doing a jam so I don't have time to learn'. Do you not see the dichotomy in this?
Is the GameObject destroyed at any point?
it work thank you
public GameObject Coin;
private void OnCollisionEnter2D(Collision2D collision)
{
Coin.SetActive(false);
SS.Score++;
SS.Health.value++;
}```
so im not getting an error but the Score and health isnt going up
i do but i added a bool to double check its not being called and its not
how do you know they are not going up
i tried changing the score whilst im in a game and well ofc it works but it doesnt work whne im colliding with the GameObject
because they are not 🙂 i have tested it
is the code even running?
check the timescale value, before hitting the WaitForSeconds then
yh so thats what im thinking as its yielding back to update and its now false
yes
Does the Coin GameObject deactivate? Are you sure the collision occurred?
prove it
in what way?
yes the collision occured the coin is then Deactivated
well i started the game i collided with the coin and the coin dissapeared yet no Score Value Added
its another Script File
but how do you know the value didn't go up ?
I know what it is, Im asking where you assigned it
Is the SS field properly assigned?
you debug code by looking at the code, not the game view
because in the inspector its still 0
ok
yes time scale is 0
ah yes then thats a problem
i have it all assigned on my canvas
Coroutines pause when the time scale is 0 . . .
im not setting it
if you want yield to ignore timescale you want WaitForSecondRealtime
yes
show where
you cannot assign SS on your canvas, it is a private variable
You have to use WaitForSecondsRealtime instead . . .
Not setting in there directly , but if it hits while timescale is 0 it wont continue
does that ignore timescale?
Yes . . .
but the SS isnt a variable im calling the score and Health Value from the other script, and in the other script its set to be public
I dont see SS assigned
that is not filling the declaration you showed in your code
I'm realising I should probably adapt my timer code to account for this
given so far you have not assigned it, your console is also in a different tab, makes me think you didn't check for NullRef at all @strong wren
You created a variable called SS in the code snippet you provided. You must assign or reference that variable to the GameObject with the ScoreSystem script attached to it . . .
oh yeah i do get a nullref error
Beg to differ this
ScoreSystem SS;
is a private variable of type ScoreSystem called SS which is Null because you do not assign anything to it
yeah code doesn't lie
Always check the console for errors . . .
if its private and you haven't assigned it else where in code, its null
ok so i did it but now how do i reset the highscore
And make sure they're visible to the console . . .
so the player can reset the highscore
The same way you reset any value . . .
ye this is the error
just make the value 0?
use the assignment operator
Test it; try it out . . .
That's game dev . . .
If I move my hand and I want to reset it, I'll move it back to a previous or a default position. The same applies to anything you want to reset . . .
so i have to attach the code to the GameObject?
yea my brain was not working
oh nvm
thats not how you assign it
it should be either done in the inspector or code with assigment operator
ye i just realized i have to Attach smth to the SS and in my case its the Canvas since its the GameObject with the code
fixed it
thanks guys

just being pedantic , but
"attaching" and assigning are kinda different terms
yep
Yeah maybe i should try game jams.
that really cool fr if you need help for find them i can give you some website or server
https://gdl.space/ayujumowac.cs Hey i have a question about this bit of code. the thing i am trying to create is a simple script for handling downforce of a car controller. when i use this bit of code the car at high speeds begins to wobble and bug a lot. how can i fix this? oh and im using wheel colliders btw
I dont know why the described error occurs, but in general you shouldn't handle physics in update, instead put it into FixedUpdate().
i dont really get a error but the car handling is terrible and not really realistic. the car is giving weird results. however for the fixed update part didnt think about that but sounds logical. i will change that see if it gives any better results
Hello, do you know how to configure the NetworkRoomManager? Can i get some explication thx
Hey everyone, quick question
i'm doing a small game for a jam, and i have a shopping cart, that can get items put into it
the items are non kinematic rigidbodies with box colliders on them
my issue is, i'm trying to get every item in the players cart, and my quick and dirty solution was just doing an overlapbox on the cart, and then looping over the stuff to check for items
but for some reason the overlapbox returns an empty array every time (the green wirebox shows the area and the position of the overlapbox, it should by all accounts get every items collider, yet it does not)
i used overlaps a bunch of times before, and never had this happen, so i don't know what could be causing it
how do you know the array is returning empty?
i printed out the array right after getting it, and log shows an empty array (second picture i attached)
the array object is there, its not gonna show it like [amountofitems] you're logging the whole array object, so its just []
try logging the Length property
itemsInCart.Length
Maybe show your implementation
it shows up properly now
ig the issue was with the stuff i do after getting the array, and not with the overlap
for some reason i remembered that just printing the array shows the contents too, which made me think it was empty lol
i should be able to fix the stuff after the overlap easily, thanks for the help
I think the only time you can see contents is via breakpoints /debugger, stepping through code
but at least its sorted now 
if you don't do it often no need to worrry, if you do this caluculation often consider using the non-alloc version
public Slider Health;
void Update()
{
Health.value -= 1 * Time.deltaTime;
}```
hey does anyone know why my code isnt working? im not getting an error, i want the slider to slowly go down every second but it wont is there any reason behind that?
What happens instead?
nothing
not possible since i only have 1 slider
hi again why when i randomRange my number (event number) i got everytime 1 IEnumerator Event() { while (true) { yield return new WaitForSeconds(timeForEvent); if (timeForEvent >= 2) { timeForEvent = timeForEvent - 0.4f; } int eventNumber = Random.Range(1,2); Debug.Log(eventNumber); if (eventNumber == 1) { missiles = missile; } if (eventNumber == 2) { missiles = missile_suivant; } StartCoroutine(missile_event()); } }
Assuming the value is updated
no, no value is going down
Integer would have the max exclusive (not accounted)
why its write inclusive in the doc
only floats are max inclusive, nowhere it doc says otherwise
oh i see ty
i have not see ty
When you log, does the value decrease?
wdym by log?
The overload for float is inclusive
Debug Log
i dont have a debug.log
@strong wren
I'm assuming it becomes zero immediately
no nothing is happending
i also expected that
Maybe the script isn't on the object in the scene if you aren't getting any logs
i dont have a log, and i dont really know how to add a log in here i cant just add Debug.log in the Update Function since thatl just well Give me a log every frame
I can't help you if you're unwilling to debug. Good luck.
i want to but i dont really know how
well in this case
Add a debug log and see if it prints anything
Hello again.
another question why i cant drag and drop my balloons gameobject in my transform public variable on my prefab (the target variable)
if i add a debug log in the Update Function thatl just call it every frame?
i can try to make it so if the value of Health Goes down then i get a log but again no value is really going down so that wont really do much
hi i have this battle starter and i want to pass the game objects to another scene, is the only way to do it use DDOL? i just want to pass them to my battle manager, but i only want to use my battle manager on the battle scene
Prefabs exists throughout the project (every scene) but objects in a scene may not exist in all given scenes thus it makes little sense to be able to reference objects from scenes that might not be active. tldr you can only reference non scene objects on prefabs.
You need two things:
- A place to store the data that will survive a scene load
- A way to find that data from the new scene
A static List<WhateverThoseThingsAre> would be sufficient, as long as you only need to pass one list of levels at a time.
thanks could you give me an example? playerprefs?
so how can i do ?
playerprefs would be inappropriate: you can't shove an entire unity object in there and then read it back

