#💻┃code-beginner
1 messages · Page 87 of 1
Yeah I did the check. and it didn't output anything. I also tried it with .gameObject at the end of the check and it crapped out again. So I'm confused as to how it found the parent Transform but not the parent GameObject.
you can make custom operators?
I might suggest structs to represent certain states and can hold many numbers of stuff (You may want to make your own == operator with this). Or make a class and use that to manage the current state. But i can't think of anything specific.
Yes.
It surely logged something, make sure the if statement is correct. It should only check for doorChecker.transform.parent == null, no more, no less
I'm more familiar with classes than structs so I think I'll try that
Oh, sorry no, the null check didn't log anything because it found the parent of all the doorChecker objects I'm cycling through. So there was nothing null.
The other stuff that I put in worked fine (log and test renaming the object).
Understandable, problem with classes is you shouldn't be spamming new on them.
In Update for example.
does it cause lag?
public static bool operator ==(ScreenVector former, ScreenVector latter)
{
return former.x == latter.x && former.y == latter.y;
}
Welp, once you made your own == operator though, compiler might wine a bit.
So you need to add these as well.
public static bool operator !=(ScreenVector former, ScreenVector latter)
{
return !(former == latter);
}
public override int GetHashCode() => HashCode.Combine(x, y);
public override bool Equals(object? obj)
{
if (obj is not ScreenVector screen_vector) return false;
return this == screen_vector;
}
how do i flip camera
No, but it can crash (i think) if you went nuts since it will eat RAM. So i guess it will still lag lol. The more fields a class have, the bigger the weight or memory.
Okay so there's no more issue it seems? As a GameObject will always have a Transform component attached, when .parent is not null, its .gameObject is not null either
And they don't get freed immediately unlike with structs. Unless that struct is a field of a class, in that case, it will only be freed if the class is freed.
? so how
Yeah, it's working properly now. I'm still confused as to why it will find the parent Transform, but Errors instantly when trying to find the parent GameObject.
Because it has no parent
No other possible cases
a.transform.parent can be, and will be null when a has no parent
I'll see what I can do, I know the logic so I just have to convert it to code xD
Sorry, I'm just trying to understand. If it can find the parent Transform, which is a component of the parent GameObject, why does it crap out when looking for the parent GameObject but not the Transform? That's what is confusing me.
Isn't he trying to do a.transform.parent.gameObject? Should have thrown NullReferenceException and you guys could have solved it faster.
From the Inspector. Rotate it back to what it was originally (Z rotation to 0) and change the game view's aspect ratio from the "resolution" dropdown at the top-left
That's what they don't seem to understand. They say that all the objects have a parent, but when they add the .gameObject at the end, it throws
So they don't all have a parent
yt
ty
nvm
in the following statement
doorChecker.transform.parent.gameObject
There are only 2 possible ways that it will throw a Null Ref Exception
- doorChecker is null
- parent is null
cant find it
I just added .gameObject to the 'null' check and it threw an exception. Which is even more confusing, because if it's null it should just log the error.
no
No!
It's .parent that is null!
Hierarchy is made with the Transform, so that one holds parent-children information
Its in the game window
If i have to put it in another way, instance of classes hang around. And someone needs to clean up the mess but still sticks a while.
If we're finished using structs, we would throw them away immediately. But with classes, it's like we leave them around the counter for a while until your mother asks you or your brother if someone uses it and then your mother realises, she have to throw it away cause no one needs it anymore. (There's no more classes that references it)
Okay, still a bit confused about it tbh lol, but it's working now. Thank you for the help guys.
Man, you really need to understand this stuff because you are looking for a shit load of problems if you don't
I'm trying. lol.
When asking about why something doesn't work. Please mention if there's a red warning sign right in the console first and foremost. 
Also what's the name of the Exception, and the line it occured. 
Question for you. Given this code: someObject.transform.parent.name, which gets the name of the parent object in someObject - In the Hierarchy, the object in someObject has no parent. Which one of these will be null, to signal there's no parent?
someObject.transform.parent.name
One possible answer only
lol. Wouldn't let me just put the answer. But 3.
Correct
I do understand that part. The thing that's confusing me is being able to find the transform, but not finding the transforms GameObject, if that makes sense?
The problem you had was that the parent is null. And you're trying to access the gameObject of a non-existant value from: parent.
someObject.transform.parent - is found.
someObject.transform.parent.gameObject - is not found.
It's the difference between finding the two that's the confusing part.
The first one - it's not found, because it's null
parent wouldn't throw a NullReferenceException because it did it's job. It's giving you null or a reference to a transform object.
Transform:parent returns null if the Transform has no parent, it's in the docs
It only throws NullReferenceException when you try to get through something that doesn't exist.
That means that getting null by itself, isn't a problem, the problem is what you might do with it, which is where the exception is getting thrown. :0

string str = null;
Debug.Log(str.Length); // NullReferenceException! 'str' is null, can't access its 'Length' variable
Sorry, I really don't mean to sound really stupid, just honestly trying to understand the 'why' of it.
If the code can find the parent transform, which lives on the parent GameObject, why can it not find the parent GameObject?
I don't understand how the GameObject can be null if the Transform isn't. Does that make sense at all?
It cannot find the parent transform, and it tells you that by giving you null
But it can. It works fine finding the parent Transform, but not when I try to find the parent GameObject.
What do you mean exactly by "find" here? Like being able to type it in the code?
It's vastly different than what can happen when the same code runs
foreach (GameObject doorChecker in doorCheckers)
{
Debug.Log("I am a door checker");
if (doorChecker.transform.parent == null)
Debug.Log(doorChecker.name + " has no parent");
Transform doorRootObject = doorChecker.transform.parent;
Works fine, finds the parent Transform.
foreach (GameObject doorChecker in doorCheckers)
{
Debug.Log("I am a door checker");
if (doorChecker.transform.parent.gameObject == null)
Debug.Log(doorChecker.name + " has no parent");
GameObject doorRootObject = doorChecker.transform.parent.gameObject;
Throws an exception, can't find the parent GameObject.
This is the part I'm struggling to wrap my head around.
Well, it does. 😕
No, it doesn't
if transform.parent is null , it is null, it gives an exception error because u said transform.parent**.gameobject**
It does not throw an exception because because you're not doing anything with doorRootObject just yet
Try to access anything on that and you'll get the NullReferenceException
u used the null value
Heey, hi everyone... Could someone help me with this? ```cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class LoadingScreen : MonoBehaviour
{
private float loadingCanvasTime = 2.2f;
[Header("Drag")]
[SerializeField] private GameObject loadingCanvas;
[SerializeField] private Animator loadingCanvasAnimator;
[SerializeField] private Animator loadingTextAnimator;
void Start()
{
StartCoroutine(CanvasTextFade());
}
private float time;
private IEnumerator CanvasTextFade()
{
loadingTextAnimator.SetTrigger("ActiveLoadingFadeText");
yield return new WaitForSeconds(loadingCanvasTime);
loadingCanvasAnimator.SetTrigger("ActiveLoadingCanvasFade");
yield return new WaitForSeconds(0.3f);
loadingCanvas.SetActive(false);
}
}```This code is responsible for controlling the initial loading screen of my game. As you can see, it takes 2.2 seconds to disappear from the start of the game. For this reason, I would like to create a function, similar to Start or Awake, that can be accessed from anywhere in the code within the project. When calling this function, I want it to execute 1.1 seconds after the loading screen starts. The purpose of this is to free up Awake and Start to achieve a smoother and more dynamic start. Maybe it’s silly… but I have the feeling that it looks less fluid when I call too many functions in Awake or Start.
Let me put it like this, transform.parent gave you the answer I didn't found anything which is equivalent to null.
There's nothing stopping it from giving you that answer because it's completely valid.
You can do stuff like.
if (transform.parent == null)
Then deal with yourself.
Or if you try to use it anyways, the runtime will get mad like what happened with transform.parent.gameObject. You asked for the transform and it gave you its transform. And then you asked for its parent, it answered with null, it didn't have a parent. And then you tried to get gameObject with it, but the parent beforehand answered with null and it's having problems with that.
gameObject here isn't null, the parent is.
class.functionA.functionB.parameterA
if functionA is null
functionA.functionB will return an exception
because u used functionA to execute functionB
!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.
foreach (GameObject doorChecker in doorCheckers)
{
Debug.Log("I am a door checker");
if (doorChecker.transform.parent == null)
Debug.Log(doorChecker.name + " has no parent");
doorChecker.name = "ThisIsWhoseParentImTryingToFindAndMyParentIs" + doorChecker.transform.parent;
Transform doorRootObject = doorChecker.transform.parent;
The console will hold the essential information here
Look for "<some name> has no parent" messages
Does null reference converts to "null"?
Empty string, IIRC when concatenating
Ah.
I never tried it, i always assumed that it does ToString() in the method and would just throw a null reference error.
There is at least one more "DoorLocked (clone)" object that has been cropped out of the screenshot below
And i always do object?.ToString() ?? "null" anyways.
Yeah same, can be shortened down to obj ?? "null" in most cases. But watch out as ?. and ?? don't work properly with Unity objects (it bypasses their destroyed-but-not-null-yet state)
Try a more explicit version so it doesn't get drowned out by the other logs
That's the entire console
Use Debug.LogWarning() for example
No 'no parent' entries in there.
Put this before the foreach loop
foreach (var obj in doorCheckers)
{
if (obj == null)
Debug.LogError("There is a null object in the list!");
else if (obj.transform.parent == null)
Debug.LogWarning($"Object {obj.name} has no parent!", obj);
else
Debug.Log($"Object '{obj.name}' passed all checks, its parent's name is {obj.transform.parent.gameObject.name}");
}
I'm starting to think the code you're showing isn't the one that's executing
This will, for each object in the list, ensure they're "valid"
$"Object '{obj.name}' passed all checks, it's parent's name is {obj.transform.parent.gameObject.name}"

Might as well add that extra bit in the sentence.
Good point, edited
It really does get converted to "". :p
Nothing beats creating a whole solution to check. Also longest cast I've seen lol, 19 seconds
Yeah this mf froze for some reason.
I doubt it's the cast, it's the method.
Everything came back as 'passed all checks' 😕
I seriously appreciate the help, even though I don't fully understand the why, I know the how, so for the moment that's good enough tbh. Really don't want to waste any more of your guys time. It works, so for now that's good enough.
I was thinking if you tested it right after you fixed the bug lol.
That kinda just confirms it. :p
Really do appreciate you guys taking the time, thank you.
Yep, it has a special if statement that just does WriteLine() if what you pass is null: source code
Same for strings: source code
All of this is open source, so you can peek at the internal workings all you want
The second part of the sentence asks you a question, you did that on purpose didn't you
Note that dividing a vector by zero will produce an infinite vector, so check if you have any divisions in your code
quick question, HalfLIfe 1/2 style movement. CharacetrController or Rigidbody? (Multiplayer), custom groundcheck if CC or built in?
this explains everything. thank you
Guys, I have a problem with my movement.
I can jump while my character is on the left side of the map as you see in the video, but there's an invisible wall on the right of the camera which makes my character's movement heavily limited. I can't even jump to the second platform on the right.
are you using tilemap ? maybe check the colliders.
best thing to do would be to Debug what you hit
I'm using tilemap. But the Editor doesn't show me where is the invisible wall.
hmm are Gizmos enabled? try selecting each objects.
if doesnt work just raycast and printresult
How can I do that? I'm new
private void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, 1000);
if (hit.collider != null)
{
Debug.Log($"Hit Collider:{hit.collider.name} at Distance:{hit.distance}");
}
}```
Just added your code. And it says I hit the "Ground" Layer.
this hits colliders not layers, anyway select the Ground nd screenshot
strange..
Yeah...
try remake new level in new scene see if problem is still there
Yeah I will. Btw do you want to check my charater prefab? Maybe I messed up something inside?
sure
what the hell is that lol
why is there a horizontal box collider across
your player center is def messed up af
Oh yeah that's the fall detector
no wonder ray wasnt accurate lol
I actually have problem with my charater before.
I followed this picuter in this morning
You should never have a pivotpoint like that
Shoud I delete the father and make the Sprite the parrent instead?
fix your pivot point first, if you add any objects dont put them on the root put them as child
set this to pivot
that fall detector is probably useless but move it to child object for now
I thought it already does that? Like tilting left/right when steering
WheelCollider.GetWorldPose gives you the orientation of the wheels
You can modify the quaternion it returns before applying it to your wheel visuals
I just delete the prefab and make the character object. It just become worst: Now the Character can't jump higher than that limit.
why you did not do any of the stuff I suggested?
I never understood that, i said a specific thing and you did your own thing lol
I just remake it, I put the charater sprite as root, the falldetector and the groundCheck as children and I set the option you showed me from Center to Pivot.
What did I miss?
is it moving is it sill getting stuck ?
It can move, jump and double jump, but the height limit is still there.
which height limit ? what about the getting stuck part
Oh nvm
I just realized.
That fallDetector is not "is Trigger"
So that box is the thing holding my jump height
or maybe my script is wrong too. The box is supposed to stay there and can only move left or right with the player.
Why do you have a fallDetector? Yesterday as was explained, you do not seem to need it and it seems to be causing you issues
GroundCheck being false means you are not on the ground. Which means you are jumping or falling
yes why even have that thing
If you want, you can check if the y component of velocity is negative to see if you're falling
if groundcheck == false && velocity.y < 0
I need that thing for the respawn. If I fall, my character hits the box and it will respawn.
not good way to do it
Just use the characters own collider
What you want is extremely common. But the way you're doing it is not
The standard is to check if the PLAYER gameobject's collider hits a box
guys anyone knows how to make to set an object material and change it?my script is not working ``` Material m;
public Material m1;
public Material m2;
public Material m3;
Renderer r;
// Start is called before the first frame update
void Start()
{
r = gameObject.GetComponent<Renderer>();
r.enabled = true;
r.sharedMaterial = m;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F) && m != m1)
{
m = m1;
}
if (Input.GetKeyDown(KeyCode.G) && m != m2)
{
m = m2;
}
if (Input.GetKeyDown(KeyCode.H) && m != m3)
{
m = m3;
}
}```
what exactly is not working, i dont see any debugging
Hey, guys! In order to manage in my options scene with sliders my main menu music and main game music and sound effects separately do i have to use audio mixer?
should
So, I will probably have master volume, main menu volume music, game volume music and sound effects volume something like that? I mean for groups in my audio mixer
the part of when i press the keys
Hey, i think I misunderstood.
Are you saying the fall detector is the box that the player hits for it to respawn?
You have it as a child, so it will move relative to the player and the player will never hit it
what? you debugged it?
yeah pretty much
every other game does it
@rich adder Hey! But if I want to control my menu music and main game music with just a one slider then I will need only master, music and sfx groups with it's exposed parameters right?
I mean for main and menu music one slider and for sound effects another slider
if you want
some separate it
eg In-game music maybe preferable but menu music might not
What is better to separate them or not?
As a player, what would you prefer?
To have less control, or more?
Like this? (front view)
Yeah. that's another wrong thing I did. Just bring it out and the FallDetector works again
As a player, I prefer to control them with just a single slider. Why? Because it's just more comfortable making it this way.
that meakes no sense to do it this way anyway
but if it works whatevs lol
That is kinda odd imo. Just because I don't know what "comfortable" means in this context. But ok.
I STRONGLY prefer to have separate sliders. But whatever you want and think works best is what is best
Why not separate sliders and a master slider?
You mean slider for menu, slider for main game and master slider?
What osmal said is the norm. Thay is what almost all games do
I thought that's what you meant too stelios haha
Of course have a master slider.
But also break it up
Yes, well that's what I was talking about, so did you try GetWorldPose?
Master is a group that is in default in audio mixer btw
With master I mean a slider that controls all the music mixer tracks, not necessarily the master track
Or channel, whatever they are called
(I don't really use Unity builtin audio - FMOD ftw)
Fmod is great. I learned it in college before I even used Unity. Made music tracks on it and sent it to my DAW for fun haha
Yeah love it
@boreal tangle You are moving it in Start, that will only happen once
(from #💻┃unity-talk message)
is fmod a daw?
audio engine
It's very daw-like
Wellll... you could arguably call it that yes
I sent it to Ableton though
Audio middleware is the term
oh
i see
Ableton is goat
I have ableton Push is fooon
..ops enough offtopic myb
I have a Pro Tools lifetime license I got gifted from Avid but I haven't used it in 5 years lol
🗿
@boreal tangle Since you are working with physics/rigidbodies, move the code from Start to FixedUpdate
ok thank you
banned
So did you get it working? Are the wheels tilting?
tilting wheels xD defines physics
You can do something like wheel.Rotate(0, 0, steerAngle) after using GetWorldPose
They do tilt IRL tho!
Just like you have to lean left/right when on a bicycle
When turning
To maximize [some physics term]
ohhhh like side to side tilt yeah more common in 2 wheeler
idk why i thought front to back xD
Ok and I have told you how to do this
What is confusing you?
You should have separate objects that just hold the MeshRenderer of the wheel
Rotate those, don't touch the object that has the wheel collider
Why?
Looks like that's not possible, the wheel collider aligns to the parent rigidbody
Hi, nooby unity coding question here.
I have this in my start function
Vector3[] verticies = new Vector3[4];
Vector2[] uv = new Vector2[4];
int[] triangles = new int[6];
verticies[0] = new Vector3(0, 1);
verticies[1] = new Vector3(1, 1);
verticies[2] = new Vector3(0, 0);
verticies[3] = new Vector3(1, 0);
uv[0] = new Vector2(0, 1);
uv[1] = new Vector2(1, 1);
uv[2] = new Vector2(0, 0);
uv[3] = new Vector2(1, 0);
triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 2;
triangles[3] = 2;
triangles[4] = 1;
triangles[5] = 3;
Mesh mesh = new Mesh();
mesh.vertices = verticies;
mesh.uv = uv;
mesh.triangles = triangles;
GameObject hex = new GameObject("Tile", typeof(MeshRenderer), typeof(MeshFilter));
hex.transform.localScale = new Vector3(30, 30, 1);
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
meshFilter.mesh = mesh;
meshFilter.sharedMesh = mesh;
hex.GetComponent<MeshRenderer>().material = material;```
The "Tile" game object gets created but the mesh is empty (See photo)
Could someone please help me
This is pretty advanced stuff, doing mesh triangulation.
Beyond what I know
Nvm, asking the question made me realize that I used the gameObject variable instead of hex
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private float horiMovement;
private float vertMovement;
private float movementSpeed = 5f;
private float jumpSpeed = 5f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
horiMovement = Input.GetAxisRaw("Horizontal");
vertMovement = Input.GetKeyDown(KeyCode.UpArrow)? 1f * jumpSpeed : rb.velocity.y;
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horiMovement * movementSpeed, vertMovement);
}
}
Does someone know why the player cant jump with this code.
what value does vertMovement get when the uparrow key is pressed?
5.0f
change the jumpSpeed to 10000f to see if the player jump
ok
correct and what value does it get 1 frame later when Update runs again?
change it to anything you like, player will never jump
but if I hold it down shouldt it jump
GetKeyDown is 1 frame process
no, KeyDown only fires once
The current y velocity?
so getkey would work
not really. You should use KeyDown to set the vertMovement and KeyUp to reset it
hey, trying to get the mesh renderer from this video to work on my project but it doesnt actually render, any help? also can i link the video here directly?
ok thank you
Yes you can link the video
In this second instance of my mesh generation journey, I show how I use mesh filter and mesh renderer to procedurally generate and render an arrow which I can make longer/shorter/wider/thiner in real time. Basically an arrow mesh with more flexibility than an arrow sprite. Rotation is handled by the transform.
Arrow Generator script: https://pa...
here it is
so far ive copied the script from the description, made an empty object, put the mesh renderer in, assigned the default material, put the mesh filter in, then the script. nothing really happens after
Did you press play?
yeah, messed with the values while play was pressed too
for context im trying to make an educational thing for my college thesis around vector math and stuff so i need to visualize the vectors
need a way to be able to render arrows based on rng'd values
oh i guess more context im working in unity 2d
Maybe the object is behind your camera or something. Check the positioning
oh, how should it look like?
It should be in front of the camera
i have it under canvas, would that work?
Object at (0, 0, 0)
Camera at (0, 0, -10)
Object is visible
No, you don't put a MeshRenderer on a canvas
Canvas is for UI
Create the object from scratch. It shouldn't have a RectTransform
RectTransform is for UI, it got changed when you put it in a canvas
Or maybe there's an option to swap to a normal transform, i forget where
Also not sure if that shader/material is going to show
gotcha let me try again
works now thanks man
doesnt show up before pressing play, is that normal?
Yeah that's how it seems to work. Mesh is generated at runtime
ok new problem
seems to render under my background, should it be placed after?
hmm even placing it after it still renders under
here you go
It's UI so it's rendered on top of everything else. Would make more sense to use a world object like you do with your arrow
SpriteRenderer for the background maybe?
gotcha, also is there any quick way of making the arrow black?
(Take it out of the canvas too)
Make a black material and assign it on the MeshRenderer
gotcha
hmm just a sprite renderer on the top level doesnt seem to work
Idk but it doesn't seem like a code issue anymore, #💻┃unity-talk
never mind im a dummy forgot to resize it lmao
how do i like scale it properly like with the canvas
Hi! I created a settings menu to change the volume of my effects in the game. I created a mixer and this script to change the volume (also exposed the volume parameter in the mixer)
// using's omitted
public class SettingsUI : MonoBehaviour
{
public AudioMixer audioMixer;
public Slider effectsVolumeSlider;
public void Start()
{
float effectsVol;
audioMixer.GetFloat("effectsVol", out effectsVol);
effectsVolumeSlider.value = effectsVol;
}
public void SetVolume(float volume)
{
audioMixer.SetFloat("effectsVol", volume);
}
Everything works fine if I run the game in the editor, but in the build, the volume doesn't change at all (if i go to the main menu and back to the settings menu the volume stays at 80db)
I have this interface:
public interface IEncounterable
{
public static event Action<string/*encounterID*/, string/*encounterStateID*/> OnEncounterActivated;
public void ActivateEncounter(string encounterID, string encounterStateID)
{
OnEncounterActivated?.Invoke(encounterID,encounterStateID);
}
}
and I want to call ActivateEncounter() in this way:
case ENCOUNTER_TAG:
string[] splitId = tagValue.Split(",");
if (splitId.Length == 2)
{
ActivateEncounter(splitId[0], splitId[1]);
}
break;
the script this code is in has IEncounterable but doesn't see ActivateEncounter() as a method.
am I missunderstanding interfaces?
Interfaces is more for OTHER classes calling that method
You need to create the method in the class that inherits from an interface
Also in unity, I don't think the c# version allows default implementations? But I'm not positive
Hey everyone! Can you guys suggest a beginner unity tutorial? I've used to have experience with unity but it was 2015 or so hence most of the stuff I remember is irrelevant or outdated. I know basic C# and overall programming and my goal to make simple small games, mostly low-fi 2D. There's just too many videos and it's really hard to choose a single one from this whole plethora of content.
My requirements are basically:
- Something simple, I'm not going to use net code, advanced graphics or make complicated systems so I need something that's easy to follow and doesn't use redundant features.
- A preferably a series of videos, I think it's almost impossible to teach all important stuff in one video.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
so it has to be abstract?
Well, you can do abstract if you want 🤷♂️
you mean learn unity dot com or what?
well I don't, I just want to call that function
Well, then you gotta make that function.
I feel like I missed part of a conversation haha
I think I just don't understand how to use an interface xD
interfaces aren't inherited 😦
don't wanna get all pedantic but diff between implementing and inheriting
when you "inherit" you are always restricted/limited to your. base class at the end of the day and you're only part of that "hierarchy"
Implementing is more modular and Many things can have something in common without being connected otherwise
Think of an interface as a remote control. The class human calls a method called change channel on the class television. Human doesn't need to know how the television implements that method. And tv can change how it implements it (like when they went analogue to digital) and still just show the "change channel" method. So nothing changes for Human
Interfaces are more of a contract where you do a pinky promise that you'll implement the fields and methods of the interface into your class. So if you don't implement it then you won't be able to use it within the same class. Other classes can call these methods as they truly believe that you did what you had to do and implemented these methods as you should
I believe you can do "default implementations" but these will be just seen as virtual and you can override them and then use them
I get no errors in the logs of the built game
@modest dust interfaces only have props not fields but yea
Ah yeah, props, my bad
screenshot your canvas scaler's inspector
did I misunderstand you can't move the slider in build ?
I can move the slider in the build, but it wont write the volume to the mixer
ohh
ok I implemented the ActivateEncounter method but it refuses to let me Invoke the event...
Hi guys, is anyone here knowledgeable in dialogue system?
If i exit the settings menu and go back in it the slider will reset all the way to the right
wdym refuses..
it's like SetVolume doesn't get called at all
hmm put Debug.Log inside and check the build ?
not allowed
is AudioMixer a custom class 🤔
Hey guys, I'm creating a basic 3rd person game with a static camera. I was wondering how I could get the player character to look wherever it's going, I've already scripted the movement. Thanks in advance ❤️
thats not how you invoke event , neither its how you subscribe to it lol
This was my attempt.... 🙂
I forgot to add ?.Invoke cuz I was trying to fix it
still same error though
and yes it gets called
transform.forward = input.normalized
try
hello anyone knows the formula for creating a random point at a specific distance from another point
what about the build, how are you debugging the logs there
dont cross post
Events can only be invoked from the class that has declared the event. But you're trying to invoke it as if it was static 🤔
r*random angle
i built in development mode to see the logs, and no it doesnt change the volume of the mixer
what would that be in code
does that not work?
I remember doing something like this before
should I just make a singleton EncounterManager instead of an interface? xD
It only works when I hold down the key, if I release it, the character looks in a different direction. Btw, does .normalized normalize all the values in the vector to -1 to 1? Thanks
so where are you saving anything ?
or is it just not setting at all
I am just trying to change the value of the volume of the effects mixer group
put it inside if(input != Vector3.zero)
and yeah it clamps the value
No, you invoke it from the class that implements it. If you need to trigger it from the outside, then you can make a public method which invokes the event, and call that public method
the code:
random quat*vector3(r,0,0);
```it should give you a random position on sphere surface
the slider moves but the numbers wont print ?
There's Random.onUnitSphere that can give out a random direction if you want!
I am trying to invoke the event from the class that implements the interface but it won't let me
I'm not sure what else you mean.
they print...
Show all the code
public void SetVolume(float volume)
{
Debug.Log("Setting volume to " + volume);
audioMixer.SetFloat("effectsVol", volume);
}
@neon ivy
!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.
Guys, does anyone know how I can change the material of my model? This code does not work for me but in reality it does because in the debugs it is shown that it is fine but it does not change the material and I also want that if the material is the same as the material that I want to change, the code is not executed (eg: change color black the weapon but it already has black color so it does not execute) ``` Material m;
public Material m1;
public Material m2;
public Material m3;
//SkinnedMeshRenderer r;
// Start is called before the first frame update
void Start()
{
m = gameObject.GetComponent<SkinnedMeshRenderer>().material;
//m.enabled = true;
//m.sharedMaterial = m;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F) && m != m1)
{
m = m1;
Debug.Log("F pressed");
}
if (Input.GetKeyDown(KeyCode.G) && m != m2)
{
m = m2;
Debug.Log("G pressed");
}
if (Input.GetKeyDown(KeyCode.H) && m != m3)
{
m = m3;
Debug.Log("H pressed");
}
}```
Im talking about the build though
and does dev mode print debug.logs? its been a while, i just use onscreen console asset
ohok . so you see other logs but not that one ?
i see the log
the SetVolume function gets called
audioMixer.SetFloat("effectsVol", volume);
but this line isnt doing anything
Audio mixer volume operates on a logarithmic range, setting a value that is between 0 and 1 won't do much
wait random quat? is there a built in function for that
it sets a value between -80 and 0
Thank you so much it works now 😄
Log10(vol) * 20 IIRC
but why it works when i run the game in the editor
read spr2 comment
https://gdl.space/lumisekehu.cpp
top is the interface, all the way at the bottom is the implementation
are you like physically hearing these sounds
yes, and the volume changes accordingly
except in the actual build the volume doesnt change at all
so i change the slider's min max to 0 and 1 respectively and Log10(vol) * 20?
whenevr you change value in script you add the Log10 line
so the value from the slider
An interface is a contract of properties and methods that you need to implement into your class
the audio plays loud in build but volume wont go down right ? just to make sure i understood lol
You need to add public static event Action<string/*encounterID*/, string/*encounterStateID*/> OnEncounterActivated; into your class and use that, not InterfaceType.Event
yes
ill try log10(vol)*20
at that point I should just use a singleton to handle this event instead of implementing it in every single script that I want to invoke it from
I'm just trying to force an interface into this while it really has no place being there
yeah no change
Well, you need to understand that an interface is not an extra class slot to have extra inheritance. It's a contract to implement your own, custom behaviour for the methods and properties listed in the interface (so that two classes can both have, for example, a PrintDetails() method, both are called in the same way, but one prints details of how a car is made and the other prints details of a shopping transaction)
If a singleton is what will help, then go with it

all I wanted was to call an event from any script that has the relevant data
for some reason I thought interfaces were the way to go for that. but it's not
Hi guys, any reason why it doesnt show the canvas for my Dialogue system? theres no error thats why i cant trace whats wrong
The Mesh Renderer is disabled on that object
Not sure if that's intended, but that will "hide" the mesh
If it's meant to just be a detection area, then it shouldn't have a mesh on it
Transform, Collider, scripts
if you want to visualize the range you can use gizmos
like this?
No Mesh Filter, no Mesh Renderer
My problem is there is no error, i cant find the problem
I need to remove the mesh filter, renderer?
Well yes, you don't need it to be visible, that will be more performant
I have this script in the script execution order and It's not printing anything on the console. Why?
I also tried putting the Debug in an Start and as the first line of the Update but seems to not be working at all
probably there is no instance of your script on gameobjects
ooh
"No asset usages" indicator above the class - yep
So I need to have a gameobject with the script attached in the scene for it to work
that would be an instance yes
I see, thanks guys
public class SettingsUI : MonoBehaviour
{
public AudioMixer audioMixer;
public Slider effectsVolumeSlider;
public void Start()
{
if (PlayerPrefs.HasKey("effectsVol"))
effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
else
{
PlayerPrefs.SetFloat("effectsVol", 1);
effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
}
}
public void SetVolume(float volume)
{
Debug.Log("Setting volume to " + volume);
audioMixer.SetFloat("effectsVol", Mathf.Log10(volume)*20);
PlayerPrefs.SetFloat("effectsVol", volume);
}
public void GoBack()
{
SceneManager.LoadScene("MainMenu");
}
}
this is my new settings controller, it doesnt change the volume mixer in the build, everything works as it should in the editor
`List<Vector2> edges = new List<Vector2>(pointCount);
Vector2 previousPoint = new Vector2(0, 0);
lineRenderer.positionCount = pointCount;
for (int i = 0; i < pointCount; i++)
{
previousPoint = edges[i] = UnityEngine.Random.insideUnitCircle.normalized * dist + previousPoint;
lineRenderer.SetPosition(i, new Vector3(edges[i].x, edges[i].y, 0));
}`
why is the edge index out of range?
The list is empty. You need to .Add() elements into it. Can't access them with [i] to add a new element
Consider using an array Vector2[] instead, that is pre-filled with a set number of values
oh i see
How can I keep aspect ratio like this in Unity easily? Could you recommend me a guide or tutorial? I cannot find it, everything I see is how to keep positioning for UI
This covers how to scale an orthographic camera
https://pressstart.vip/tutorials/2018/06/14/37/understanding-orthographic-size.html
Thanks a lot
is it possible to get rid of the read only property?
how can i acess a scirpt thats on my player on a prefab? cause when i try to drag the player from the hierarchy to the prefab script it doesnt seem to work
quick question does anyone know why after four seconds my game object doesn't tick back on
IEnumerator Untick()
{
if(canUntick == true)
{
pointTrigger.SetActive(false);
yield return new WaitForSeconds(4f);
pointTrigger.SetActive(true);
}
}
try putting yield return new WaitForSeconds(4f); before pointTrigger.SetActive(false);
Coroutines do not run on disabled/destroyed objects, are you disabling/destroying the object this script is on?
Is pointTrigger the object that's running this coroutine?
ok
prefabs cant reference scene objects like this. The prefab isnt guaranteed to the be spawned in that one scene only. You need to instantiate the prefab at some point, then plug in whatever references after
after i instantiate the object how to i plug in the refrences after
okay ill try this out ty
why isnt this line of code making my character move? removing deltatime fixes it
rb.AddForce(movement * (moveSpeed * Time.deltaTime));
Deltatime decreases the force by a factor of 100
The force is still there, it's just not noticeable
At a stable 60 FPS, delta time is 1 / 60 or 0.016
The time in seconds since the last frame
Using deltatime for applying forces is not recommended anyway. AddForce already smoothes out the force over a few frames
You should just remove deltaTime instead
When you need massive numbers like that, it is a sign you are doing things wrong/fighting the engine
why? then my movespeed will be dependent on frame rates
It will not be
#💻┃code-beginner message
AddForce modifies velocity, which is in meters per second.
You do NOT want deltaTime in addforce at all
it is though, as i've experimented already without deltatime
you can see a clear increase in speed when i focus on the gfame window
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
You can see that the equation ALREADY INCLUDES deltaTime...
AddForce is not dependent on frame rate
so why is the speed increasing then?
You did something else wrong. Or something else is causing it
void Update()
{
// Get input from the player
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Calculate movement direction
Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput).normalized;
// Apply force to move the player
rb.AddForce(movement * moveSpeed);
isMoving = movement.magnitude > 0;
magnitude = movement.magnitude;
grounded = IsGrounded();
_animator.SetBool(IsMoving, isMoving);
if (isMoving)
{
// Calculate the rotation to look at the movement direction
Quaternion lookRotation = Quaternion.LookRotation(movement, Vector3.up);
// Smoothly interpolate the rotation
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 10f);
}
// Check for jump input
if (Input.GetButtonDown("Jump") && IsGrounded())
{
// Apply upward force for jumping
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
print("JAMPED!!!");
}
_animator.SetBool(Grounded, IsGrounded());
}
this is my entire movement code
You should also not use deltaTime in slerp haha. At least not multiplying it. Sorry
iirc you still need it in the speed calc for inputs
i thought you had to use deltatime to make things more consistent across framerates
That's why physics go into FixedUpdate, which by its name, runs at a fixed rate
oh wait yeah also its in update nvm what i said
isnt that the same thing as just slapping on deltatime?
rigidbodies movements go In FixedUpdate
consistent but they run at different intervals
It's more of a convention, poll input in Update, and deal with the Rigidbody in FixedUpdate
force * DT / mass
^ this is the calculation unity runs when you call AddForce in ForceMode.Force
DT is deltaTime.
You do not want to multiply it by deltaTime again
I'd also change the code that deals with the rotation to use rb.rotation, so it's consistent with the position changes you apply with AddForce. You'll experience less jitter as both will we applied at the same rate
i still dont understand why the speed changes then
No, not really. You can use deltaTime in FixedUpdate (and it is converted to fixedDeltaTime)
Do you touch timescale anywhere? I dunno either
no i dont
which is what led me to believe that it was frame dependent
yeah i know now
I mean... it's as simple as pointing to the calculation again
but befoer i asked i meant
No I understand
anyway thanks guys
Does someone know why my setup for buttons does not work? I cannot click on them for some reason.
You need an Event System in the scene
It's added automatically when you create a Canvas, so you most likely removed it, add one back, it's what relays mouse events to UI objects
That fixed it, thank you.
And I already tried like two hours to fix it. 
i have this TileData class
[Serializable]
public class TileData
{
public int X { get; set; }
public int Y { get; set; }
public string Id { get; set; }
public TileData(Tile tile)
{
X = tile.Position.x;
Y = tile.Position.y;
Id = tile.Id;
}
}
and I have this WorldData class
[Serializable]
public class WorldData
{
public List<TileData> Tiles = new List<TileData>();
public WorldData(List<TileData> tiles)
{
this.Tiles = tiles;
}
}
im trying to write the worlddata class to a json file using this static method
public static void Write(object data)
{
string json = JsonUtility.ToJson(data);
string path = Path.Combine(Application.persistentDataPath, "world.json");
File.WriteAllText(path, json);
}
but its writing {"Tiles":[{},{},{},{},{}]} instead of having the X, Y and Id of the tile in the list
JsonUtility does not serialize properties, if I remember correctly
Oh and you'll have to provide a public constructor that has no parameters for both WorldData and TileData so instances can be created when using FromJson<T>()
Hello, im fairly new to unity and game dev engines in general and im trying to get a player circle to slow down after the Keycode is let go by a dragforce, can anyone help me with this script?
Here it is so far ```
void Update()
{ while(rb.position.y > -3.5) {
if(Input.GetKey(KeyCode.RightArrow)) {
rb.AddForce(Vector2.right * speed);
} else if(Input.GetKey(KeyCode.LeftArrow)) {
rb.AddForce(Vector2.left * speed);
} else {
}
}
Application.Quit();
}
i'm trying to spread out object by having them lock onto points near the player rather than exactly the player.
public Vector2 spreadPositions()
{
if (clump == false && ((Vector2)transform.position - chase).magnitude < error)
{
chase = (Vector2)target.position + UnityEngine.Random.insideUnitCircle * spread;
return chase;
}
else if (clump == false)
return chase;
else
return target.position;
}
This will freeze your game! Nothing else runs when your code runs, so that while loop can never exit. I suggest you start with the tutorials
llearn
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I just added the while loop oops i never actually tested it, regardless im still wondering how to slow down movement by a dragForce is this answered in the tutorials?
the objects that are lerping are all chasing the same point,
any way or other packages you know of that can do this?
Newtonsoft.Json is the most potent one when it comes to features
It's configured to serialize properties, but you can alter its configuration to use fields instead, if needed
okay thanks ill look into it
You usually just increase the drag in the Rigidbody settings, no need to throw in any code
for some reason when i die, and my player is destroyed, the objects pan out though
Oh gotcha, thanks for the learn link and that
Simple One: Does OnTriggerEnter invoke all Colliders and how do i only use one of them? Setup on the right.
how does one call a coroutine through an event?
would i just have to make a function and call it in there?
this is what i did.
As the mesh collider is not a trigger collider, OnTriggerEnter will not be called for that one. So you can be 100% sure that when this method runs, it will be because of the box collider
i just did this i guess
its annyoing that u cant call coroutines in an event
Then i ask another one: What if both of them are? 😄
Then it's not very good practice, and you should separate them into two child objects
ah thx 🙂
if i only want to set my y rotation value but i dont wanna change the 2 others how would i do that?
You could technically see which one was triggered by storing references to them into class variables, and comparing them with the collider parameter of OnCollisionEnter, but yeah the general advice is to put multiple colliders on different objects
It's normal, because iterators (the feature coroutines use) are compiled into a big class that contains a state machine, dictating what to yield return next
What is the function in order to manipulate the rotation speed to where the value 1 means 100 percent rotating perfectly to the target and 0 means it will not rotate at all?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private float horiMovement;
private float movementSpeed = 5f;
private BoxCollider2D coll;
private bool toJump = false;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
horiMovement = Input.GetAxisRaw("Horizontal");
if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded()) toJump = true;
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horiMovement * movementSpeed, rb.velocity.y);
if(toJump) rb.velocity = new Vector2(rb.velocity.x, 10);
}
private bool isGrounded()
{
if(Physics2D.BoxCast(coll.bounds.center, coll.size, 0f, Vector2.down, 0.2f))
{
Debug.Log("ground");
return true;
}
return false;
}
}
``` does someone know why the player does not jump? I set it so the arrow key has to be pressed and the player has to be on the ground to jump. In the log it says the player is grounded but the player wont jump.
How do I seed random numbers?
Ill try it does this sound correct?
assuming you are using UnityEngine.Random: https://docs.unity3d.com/ScriptReference/Random.InitState.html
I am indeed, ty
For the second argument that would be a Quaternion.LookRotation() so you get a rotation that looks towards your direction here
Then you of course have to make the third argument vary over time, so it transitions between the two rotations smoothly
Also I would like to add that I'm going to use an animationcurve to change the value of 1
1 being instant, 0 being nothing
Yep curves can do that
awesome thanks
what if the lerp third argument is 2? wouldnt it just be the same as 1?
Lerp clamps it to the 0-1 range. Use LerpUnclamped to bypass this restriction
https://gdl.space/ecikubicac.cs
https://gdl.space/vebubowoqu.cs
I'm trying to use a lerp chasing function but each object is sopposed to chase a random point around the player, but instead they are locking onto the player's previous position regardless of how close they are to it
If I'm reading this right, does Unity set its own seed on startup? If so, would this mean the only practical reason to use InitState would be to set my own manual seeds?
yes
ah ok. Glad I got that cleared up
do you guys know what's wrong with the random chase vector i amd generating?
public Vector2 spreadPositions()
{
if (clump == false && ((Vector2)transform.position - chase).magnitude <= error)
{
chase = (Vector2)target.position + (UnityEngine.Random.insideUnitCircle * spread);
return chase;
}
else if (clump == false)
return chase;
else
return chase = target.position;
}
ahh thanks
it's not picking the points very randomly, it's locking onto the player position
wait i didn't accnt for null so it skips that? idk lemme see
if i only want to set my y rotation value but i dont wanna change the x and z how would i do that?
do you guys know why this is not working
void Update()
{
if(Input.GetMouseButtonUp(0)) {
Vector3 mouseP = Input.mousePosition;
//Debug.Log(mouseP.x + " " + mouseP.y);
Ray ray = Camera.main.ScreenPointToRay(mouseP);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit.collider.name != null) {
//transform.rotation = Quaternion.Euler(0,0, - 48.068f);
//transform.rotation = Quaternion.EulerAngles(0f, 0f, 80.976f);
Debug.Log("CLICKED " + hit.collider.name);
}
}
}
I'm trying to use the unity VCS to work on my project on two different computers. When I add the project as a remote project on the second computer there are some issues - I can mostly see the project as it was on the first computer, but any values I have set in the inspector (for serializedfield variables) are no longer defined.
Do I need to do something specific to check in changes made in the inspector? One computer is a PC and the other is a Mac if this is relevant.
since you didn't bother providing any details, i'm going to take a random guess and say you are experiencing a NullReferenceException on that last if statement line
and it's because you are checking the name property on a null collider
sure, but what if your raycast doesn't hit anything
check that something was actually hit by the raycast. RaycastHit2D has an implicit cast to bool that just checks if the collider is null so you can do that or you can check if the collider is null
alright thx
oh haha i didnt even notice i was checking if the name of the collided object is null
haha thxxx
is it possible to grab a gameobject which access a certain method on a script?
lets say i have this RemoveHealth function
when i call this from another script i need to grab the game object which accessed it
pass the object as a parameter to the method
yeah i was thinking of that
but im just wondering if theres a way to do it automatically
you can access the GameObject any script is attached to using gameObject . . .
there is not. but why would the RemoveHealth method need to know what GameObject the method was called from?
i have this damageable class
and?
and i need to know which object, this object took damage from
yeah so you'll need to pass that to the method then
but i also don't see why you need the game object
im making a damage indicator
and i need to rotate an ui element around the z axis towards that object
why does the RemoveHealth method need to know about that indicator?
it doesnt
just the object which it took damage from
the indicator is in another script
so make the object that is dealing damage alert the indicator instead of the removehealth method
Hi, my Unity is stuck on Application.EnterPlayMode
you probably have an infinite loop
📃 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.
yep infinite loop in your coroutine
also, you're using FindGameObjectWithTag in Update, this is not exactly ideal. just store the reference either in Start/Awake or serialize it so you aren't constantly using that method. it's not as bad as just a regular Find, but you really shouldn't need to be doing that every single frame
I do that cuz if I have a different hoverboard active it will detect it automatically
Doing it every frame TWICE
There are way better ways to solve that
Player.GetComponent<Character>().HoverBoardActive == false
just make the Character component know which HoverBoard is active and grab it from that instead. also instead of using GameObject variables, use variables for the components you actually care about
I’m good
Gayyssss (ejem guys) is there any form to make the player still crouch if it has a roof/object above him because the roof is smaller than his normal height?
use physics cast to determine if the player cant fit
checked in what way
like if im doing this
Collider[] objects = Physics.OverlapSphere(transform.position, secondRadius);
foreach(var collider in objects)
{
if(collider.gameObject.layer == LayerMask.NameToLayer("Damageable"))
}
the parent/child relationship of colliders is not relevant here
OverlapSphere will return all of the colliders it finds in the area specified using whatever relevant search filters provided (in this case none)
also if you only care about objects on a specific layer, then use a layermask
Physics cast? I thought it was something like check if there is an object above the player
yes a physics query like a raycast or overlapsphere would be used for that
if a collider is set as a trigger, will the overlap sphere still detect it?
depends on your physics settings or the parameters passed to your query
i think it can be useful to check for anything, then check the layer after. Like if a raycast projectile needs to destroy itself on any collision, but only deal damage to certain things
not entirely sure if thats the same case here
By default yes. See https://docs.unity3d.com/ScriptReference/Physics-queriesHitTriggers.html
"Queries hit triggers", as mentioned
alright thanks
I just saw AudioSource.gamepadSpeakerOutputType in the docs. Does this mean one can play sounds on the PS4 controller?
What do the docs say about it?
One click further in^
There still doesn't seem to be a code example though :/
Grab audio source from code, set its gamepadSpeakerOutputType to GamepadSpeakerOutputType.Speaker, done.
Sadly, my school forces us to have some Visual scripts and some c# scripts in our first semester, meaining, im not really good with any of them and it kind of confuses me how i can reference stuff over different kinds of scripts. My first question is, how do i replicate what i have in the first screenshot in c#. and the second is, how can i read the "score" variable in the second screenshot in c#
GameObject.Find even in Visual Scripting 😬
wdym?
nothing lol
not even sure how you do this. Try #763499475641172029
its easier to just learn c#
Each node usually corresponds to a function/method in C#. You can google GameObject Find for the first node. Custom event could be replaced with a UnityEvent or an Action for simplicity.
The second screenshot seems like it's setting a member field of sorts for the graph. I'm not sure you can access it from C# easily. Might need to look at the visual scripting API.
this is the script i have. i have a bow and want to only be able to shoot if i have more than 0 arrows and every time i shoot an arrow, it should add -1 to the arrow amount (score)
don't name a GameObject Score its confusing to your variable
the score itself should be Score
gameobject can be ScoreTracker or something like that
GameObject.Find returns a GameObject, not an integer.
Read the documentation
Would also advise to read this
https://unity.huh.how/programming/references
You don't wanna have a GameObject.Find in update either, you would cache the reference in start or a field in inspector
Hi, I’m trying to make a random jump animation happen when I press up (I already have the jump function and everything, just need the random animations)
the Thing is, i understand none of that, the documentation could aswell be alien language to me
Hello I would like some help with my coding :P
make a bunch of transition with integers then assign random Int
It's in english xD
XD my bad
yes, but its confusing, because i dont know what im looking for. its my first project and its due tomorrow
you waited last minute 👍 nicee
nah, today was the class, tomorrow is the presentation
So what are you trying to actually do
I need help with my unity game, I tried making a enemy AI jump attack from a video I saw but there's two problems I couldn't fix:
- Enemy won't flip to look at player
2.enemy won't jump
so it works on video but not in your script ?
show script
So what object has score
Tile tile = Resources.Load($"Blocks/{data.Id}") as Tile;
returns Blocks/{data.Id} -> Blocks/grass_tile
but its returning null
the video i sent pretty much tells you how lol
please use a bin site !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.
So they gave you a task to translate visual scripting to C# without any previous knowledge of C#? Sounds really sus.
😅
they said, visual script is easier to understand, so they made us do all the basics in visual scripts. however we need to do our own mechanics ourselves, and since there is close to no tutorials or explanations on how to achive certain things with visual script, i now have it mixed with c#
So the task does not require any mixing of visual scripting and C#?
i need discord nitro to send it all ;-;
!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 kind of does, unless i figure out how everything works in visual script exclusively in less than a day
Well, you're definitely not gonna figure out how to mix the two in less than a day.🤷♂️
Seeing how you have trouble reading the docs.
Seeing how they didn't teach you any C# yet, I'd assume that the expectations from you are not that big, so maybe try to go for something simpler that you can implement in visual scripting
Don't bite more than you can chew
!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.
NVM did it
;-;
The goal is to have a working prototype for a publishable 2d platformer by friday. i have playermovement, ui systems and everything in visual script since that was what was shown to us. i need to get enemy ai, a bow system, a sword system, weapon switching, and an arrow tracking system in there till then. i wouldnt mind doing it in visual script, however i do not know enough yet to be able to make it from scratch and in online tutorials/resources, nobody uses visual scrip so i have a hard time understanding it. Generally i find c# easier to understand, however i dont have the time to restart the entire project
i already sent the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How do I detect multiple animations using GetCurrentAnimatorStateInfo?
did you set the ground layers correct btw
could you send link video you were following
In the previous two videos we made an enemy AI that petrolled a certain area when it did not see the player caracter and when it shaw the player it performed a jump Attack .
In this video which is the final video in the jump attacking enemy ai Unity 2D tutorial Series we will combine both with our animation .
The download file for the Proj...
yes i believe so
I thought the task was given today? Sounds unrealistic to have a full game done by Friday.
Anyways, we gave you what we can. Now it's up to you to decide what to do. But without understanding C# basics and being able to read the docs, I don't think it's realistic.
btw its a playlist 3 videos
put some debug.logs inside to see whats called and what not
make sure all layers are setup (also screenshot console window)
For what? It's just a simple property with an enum value. What I'm sharing has the answer to your actual question.
i ll try to figure out hopw to do the score system in c# entirely then, i think that will be easier
can i just say im new to coding soo..
do i need to type in debug.logs
or enable it on the unity screeen
Debug.Log() or you can use VS debugger
the first line of code you should've learned in unity is Debug.Log
yeah... im more of a watch people make games and you will learn how to do it kinda person 💀
Well, there is plenty of that on Youtube I guess. I find that kind of learning leaves a lot to be desired, but you know yourself best
im just trying my best
anyways here me ss
i think u wanted the debugger enabled and see the control pannel
I notice you have three transitions going from entry to walk
yeah im not quite sure what that is
The line with arrows
ik that but im not sure what they do, theres usually only 1
can i rename the values in a vector2. Instead of x and y I want them to be min and max in the inspector.
I like having them both on one line to save space is why I want to use vector2
Make your own vec2 struct
wont be on the same line though. That's some editor script stuff
take a look at those and see if it's offered
usually you can just plug those in your scripts
okay that looks promising ty
YEP
You can make your own property drawer attribute.
Oh he already posted a pre made one.
guys help me? I am trying to solve the error of the player crouching across an object when he tries to stand up but on top of it he has a ceiling that is lower than his standing height. I did it with a raycast but now it gives me an error that I am going to send there ( code: https:/ /gdl.space/fasakiqawu.cs )
it says that the line 73 is an error
I think it generates a conflict between both parts of scripts
what error
there is nothing on 73 in the code you sent
you're missing the namespaces so sending without them is useless telling the line (•_•)
if (!characterController.isGrounded)
the only error there is characterController is null
so either you have a copy somewhere or this object doesn't have a char controller on it
I have
public AudioClip[] myAudioClips;
How do I set the certain audio clips with resources.load?
did you search the docs?
do you know how to assign something to a specific element of array?
You don't need that field if you're using resources.load
Fix your car model it was exported or imported incorrectly
What have you tried?
is this supposed to be steering? what are those arrows lol
Looks like there's an expectation of rotating and translating (moving)
is there a way to make interface implementations not give u the annoying large exception thing
What would you like to see instead?
are all of those fields interfaces?
all the fields are part of the interface
i want it to jsut set it as the usual property
like {get; set}
Interfaces do not have field members
i have this game object as UI object
how can I get its position?
I tried to use rect.transform.position and transform.position
but its position is not same as my
Vector3 mousePosition = Input.mousePosition;
Debug.Log("Event Data Position: " + mousePosition.x);
that would be part of the suspensions though ?
should be in the visual studio settings somewhere
use anchoredPosition . . .
oh, they're properties within the interface, okay. threw me off bc each property has i in front and they're camelCase like fields. check your IDE settings . . .
tires don't tilt on a 4 wheel vehicle, commonly its the suspensions that tilt the carriage. They're meant to stay flat on ground look at thread/shape of a motorbike vs car
no i just put the i to say its an interface propeties lol
https://stackoverflow.com/questions/17703277/how-can-i-make-implementation-of-an-interface-produce-an-auto-property-instead-o
is this what you're looking for
thank u bear on a lightpole
does someone know how I draw a ray so that it starts from the top right corner of the collider and stops at the bottom.
bounds of the collider x + bounds of collider Y
I tried to click on the middle position of the square, but the output isn't seem like that
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosition = Input.mousePosition;
Debug.Log("Event Data Position: " + mousePosition);
Debug.Log("rect.anchoredPosition.x" + rect.anchoredPosition);
}
what do you mean by bounds of the collider x
or I think you can just use size? you need a bit of math with that
public static class SystemCollectionExtensions
{
public static T TryDequeue<T>(this Queue<T> from) where T : Object
{
T ret;
do ret = from.Dequeue();
while(!ret);
return ret;
}
}```is it fine to use in an object pool made of queue?
I meant bounds doesnt have an x or y when I type it in visual studios
bounds is a Struct
it contains quite bit of info
Show what you typed
Debug.DrawRay(new Vector3(coll.bounds.extents.x,coll.bounds.extents.y),Vector3.down *coll.bounds.extents.y ,color);
I think you add from center first
That doesn't really make much sense. You're trying to use the extents as the ray origin position.
Maybe consider a while loop rather than do-while and invalidate for Count we well.
[SerializeField] private BoxCollider2D col;
Vector2 cornerRight;
void Start()
{
Bounds boxBounds = col.bounds;
cornerRight = new Vector2(boxBounds.center.x + boxBounds.extents.x, boxBounds.center.y + boxBounds.extents.y);
Debug.DrawRay(cornerRight, transform.right * 10, Color.red, 9);
}``` 🥣
thank you
General question, is there a simple function to static batch objects that are instantiated? I have larger objects that spawn later and they aren't being batched
Dw, empty q is already accounted
(This is originally called like this anyways, TryDequ is just upgrade of Dequ)```cs
t = floatingQ_ws.Count > 0 ? floatingQ_ws.TryDequeue() : Instantiate(template_ws, transform, false);
oh i see
the problem arise when theres only 1 item, and it's null
Aye
ig i can just get rid of the ternary and just let the entire extension to handle every case
Cross posted from #archived-code-general message
(don't cross post)
apologies
You could probably just do while count greater than zero T ret = dequeue if ret not null return ret return problem
public static T TryDequeue<T>(this Queue<T> from, T desperateReturn) where T : Object
{
T ret = from.Dequeue();
while(!ret && from.Count > 0)
{
ret = from.Dequeue();
}
return ret ? ret : desperateReturn;
}```maybe this is better
lemme logic test
can anyone help me this
the position won't be the same as your mouse position. it gets the position of the pivot relative to the anchors. the same with using RectTransform.position: this gets the position of the object (where its pivot is located) . . .
yea, should work, lemme actually run it
so how can I get/convert it to my mouse position
ahh the instantiate will be called always ig, yea i dont want that
i mean i want to sync it with my mouse position
I can maybe just use a func hehe
sync what? what are you trying to do?
i want to get that object position output that is same as my mouse position when click
Log the mouse position and anchor position. Likely one or the other isn't within the same coordinate space.
t = floatingQ_ws.TryDequeue(() => Instantiate(template_ws, transform, false));
```this pool looks better than the original 
public static T TryDequeue<T>(this Queue<T> from, System.Func<T> desperateReturn) where T : Object
{
T ret = null;
while(!ret && from.Count > 0)
{
ret = from.Dequeue();
}
return ret ? ret : desperateReturn();
}
```the pool btw, if anyone wants
the object will always return the position of the pivot. is the UI object inside of a canvas?
yeah, but im not sure what is the anchor position coordinate space to convert
yeah
here is my canvas
you should not have to convert anything. ui objects are in screenspace similar to the mouse position . . .
Maybe check count before dequeuing anything and return inside the while loop with an if statement on not null to avoid having the return value outside of the loop or having the extra dequeue statement. #💻┃code-beginner message
but I dont understand why I click on it, the position of that square and my mouse isn't same
yea I quite changed the declaration of ret first to null so the first check will fail and the Count will check too
public static T TryDequeue<T>(this Queue<T> from, System.Func<T> desperateReturn) where T : Object
{
while(from.Count > 0)
{
T ret = from.Dequeue();
if (ret)
return ret;
}
return desperateReturn();
}
that looks cleaner and simpler, rigt
lol im writing it too complicated
id try to write this in a way where you dont need to provide a delegate everytime. store it on the class rather than giving it as a parameter
Queue has a trydequeue method btw
[SerializeField, Required] CinemachineVirtualCamera virtualCamera;
internal void ToggleCamera(InputAction.CallbackContext _)
{
virtualCamera. // is there a field or property to access that "Body" ?
}
```Hey, how do I modify body selection of `CinemachineVirtualCamera` using scripts?
*Don't ask to ask:* ||The main goal is to make some toggle button to switch between 1st and 3rd person camera view||
You could do this but the best practice in Cinemachine is to just have two virtual cameras and switch between them
The thing is I can't add another CinemachineVirtualCamera component. Did you mean to create completely another game object?
What is the function that uses speed rather than duration needed to get to a rotation? Right now im using Quaternion.Lerp but i would like to set a flat speed instead.
Yes... Why would you want them to be the same object?
Lerp actually does a flat speed when done properly. But you are probably looking for RotateTowards
Thanks!
I dunno, that's the only thing I thought about, to add a second component with 3rd person view properties and switch between them 😂 I didn't think about creating a completely dedicated game object for that, thanks a lot!
A simple solution but I was forcing scripting way, meh... 
I am trying to run Lightmapping.BakeAsync(); but it is saying it is not allowed in play mode. Is there an easier way to bake the lighting during the game?
Hello. I've got this problem I still couldn't resolve. I have a .txt file with 4 million words in it and my script is supposed to display a random excerpt from it when I press C. But the first time I press it, sometimes, but not every single time, the game freezes for a couple of seconds. How could I fix this?
This is basically my code. And I've yet to find a way to fix this.
Any idea or workaround would help.
I mean you loaded a file with 4 million words and ran Split() on the text
Thus making a 4 million element array
Could this be the problem?
I remember seeing you ask this before, but just curious why do you even need such a large file? What 4 million words could you possibly need
The split is less of a problem than loading such a huge file in the first place
I/O is notoriously slow
IT's supposed to be a game mechanic called intrusive thoughts and I included every story and piece of fiction I've written throughout the years as part of my "dream-game" :D.
The English language has like 300k words max
They're stories and what not.
But you're just picking a random word
Script isnt loading for me so I cant see what you're doing with the file, I think you would have a better time splitting each story into it's own file
Oh, I deleted it, sorry.
I'll repost it.
But won't that cause even more problems?
I mean, I could split the .txt file in 4, 10 or 40 files, but wouldn't cycling through them cause even more freezing problems? And even more often?
well, depends how you're loading it all in
Why would you cycle through them? You just wouldnt be loading 4 million words at once, you would be loading way less
That coroutine also doesnt need to be a coroutine, since its just yielding after all the code has run
If you only need to display a phrase or word at random, you could roll a number to pick one of the stories at random, then from that, randomly pick a word from that story, you then shouldnt need to loop through anything
I'll try splitting it in multiple files, thanks.
can someone help fix my code?
i donr even know any languages fully
¯_(ツ)_/¯
Depends. Post the code and ask your question
Can someone help fix my cod!?!?!?!
-dosnt provide the code
-doesn't provide the error
-doesn't know what they are doing
-🤷♂️
mean i asked if anyone would be offering to help
i diddnt want to spew my code here
No one will commit to helping you without seeing the problem first
How would people know if they can help, if they dont know what you want help with
We can't help you without seeing the code🤷♂️
You're probably expecting some "private help". This is not the place for that. Some people do that as a job and get paid.
#854851968446365696 how to ask for help
Im guessing you didn't even look it up on google or try to debug it
!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.
hi, I need an item button box to open under my pickup script. does anybody know why this may not be happening? ive looked through the tutorial a few times, I i think I'm just not understanding
i was wonder how to turn my mesh into a ragdoll if that is possible
your !ide is not configured, there is a clear spelling mistake on the line you are hovered over. Your IDE should be telling you about it
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
okay thank you!
there is a ragdoll wizard you can use, your object must rigged properly though. If this is all just one object, then you cant really ragdoll
am i able to rig it in unity i hate blender
i dont think so, im not a 3d modeller (or whatever the term is). You'll need the object rigged regardless if you want animations so you should do that in blender
assuming you made the model
thank you
After that part, making a ragdoll is quite easy. theres a lot of tutorials online for it, but the general steps are
use the ragdoll wizard
disable all the ragdoll colliders, make the rigidbodies kinematic
enable colliders, make rigidbody not kinematic when you want it to ragdoll, disable the main movement code
I have the no collision with its self and stuff but I just recently started unity and the problem I mainly have with my characters is the rigs/bones. I can never set them up no matter what program I use.
you can download models online so you can prototype easily, they will come rigged already
when I do try that they are either paid for or don't have the rigs
im sure a majority of 3d characters online are gonna be rigged already. I just use mixamo to get them
ok i'll look there, I've been using "Sketchfab"
Hey yall i got a question.
In my current project i have a level select screen.
I opted to make it a scroll view so the player just has to scroll up to see new levels or down to see previous levels. (Something like the candy crush level layout).
My only issue is. Im trying to save the level that the player is currently on.
Eg. If they on level 50 and they exit the game and go back into the game i want the level to show as level 50. I dont want it starting at level 1 again and then they have to scroll all the way back up to level 50.
So does anyone know how i would be able to save the position of the current level the player is on?
My levels are not prefabs. They are images that have a button script on them. And i setup my level layout (type of board, goals, etc) in a scriptable object
Sorry for the bad explanation. Im not sure how to ask this question.
Im using unity and c#
Are these images contained under 1 parent/container or in an array that references the image in the scene? If so, you could use the level number as the index (with respect to 0-based), and scroll to the image at that lvl number, otherwise, you could save the Vector3 of the anchored world position if its UI, or world position otherwise, though I feel like there should be other ways you can compress your data aside from relying on 3 floating point values
Save the current level index/id. When opening the menu, load that data and scroll to the appropriate level.
I made a scroll view in my hierarchy and it auto gave me a view port, content, scroll handle etc
I made my images in the content section.
I think my scriptable object for my levels is an array. Sorry i made that quite a while ago. So im not 100% sure.
I made a scriptable object called world. Then another one called level.
In my world SO i think i select how many levels i want the in my level SO i do the setup of my levels (moves, goals, layout etc).
Im not by my pc right now so i could be wrong.
Im still quite new to coding.
I have managed to get this far by following random tutorials when i got stuck.
So im not too sure how to do what you are suggssting😅
I have an issue. With my game, I start with an object disabled. Later, it's then enabled using SetActive(), however it doesn't then loop Update()s, it just does nothing. Do I have to kickstart it running updates through it or something?
Which part exactly?
All of it 😅
you just need to set it active. I would check if the script is disabled, maybe u have something returning early from update, maybe theres an error and its not running, maybe its just the wrong object you're looking at
So I'm making a game where you cook foods and give them to customers, I store the foods that are in your inventory as a list of gameObjects. I made a customer scriptable object that has a list of potential "Foods" (another scriptable object). How would I check if the player has the corresponding food in their inventory? This doesnt seem to work
Good thinking. It's worse than just the script being disabled. I forgot to add the bleeding script to the new object. Thanks for the help 😂
Then break it down and research/ask about each thing separately.
This doesnt make a whole lot of sense, is your SO holding a reference to an existing GO?
Itd make more sense to do it backwards, store which SO the gameobject came from. Then check if the player inventory contains any of the SO
Checking the gameobject looks like it added more complication
so should I store a list of foods in my inventory instead of gameObjects? on my SO's i dont have any references to gameobjects, to access the SO on the object I would have to GetComponent<FoodScript>().foodData; which holds the scriptable object
heres what my customer looks like
I would store a list of FoodScript instead of game object. But also i dont know what your script is doing currently then, if each customer has a list of SO, and you are checking if your game object list contains the SO.GameObject(). What is that .GameObject() for then
the .GameObject didnt work
here's what I came up with. It works but I want to know if theres a better way
the better way would not be storing a game object at all, and just be storing the FoodScript directly. Otherwise, this seems relatively fine
storing a list of food script would avoid N get component calls
ah so like its one layer less abstracted you could say
What's the operation to add/substract (not set) to an int variable?
thats one way to put it, its the same outcome except you just avoid a GetComponent call. its more expensive than a .gameObject but u wont notice performance diffs
What does the red line say?
And what is the goal of that line of code?
If you want karma to be 5 less, then you want -=
But that IS setting...
I'm doing a semi text adventure and an action in the game when you press the X key will lower your karma by 5
I do not want it to be set to -5 but rather go down by 5
-= then
But that is setting. It sets it to 5 less than the current value
Also, your error is saying that you would have needed to do something with that operation. Like int1 = karma - 5
You can't just have the operation by itself and not use it
Hello again, I need some help with my script my keys A and D are inverted and im not sure how to fix it, The character also moves pretty slow and was wondering if there is a way to speed it up.
you have a negative sign in your multiplication for horizontal movement
definitely do yourself a favor and do basics of c# courses. you really wont have a fun time trying to make any game if you dont know how to subtract from the current number
Remove the -
is that really it?
Of course. You are negating the direction of the vector
a is left and d is right
and dont multiply the output of GetAxis with deltatime
as for it moving really slow, you currently only move 1 unit per second because you are not scaling by a speed variable
I'm learning in one of my hs classes and the notes he made us do were on a unity project that's on my workspace on campus, I tried to look at documentation but I couldn't explain it in a way that gave me the results I wanted
oh shoot thank you I feel so stupid
It's all good! Don't feel that way
would i add a speed varible to it to increase it?
scaling = multiplying
i suggest making it a controllable variable too, then you can think about adding walk speed, sprint speed, crouch speed, etc
Moving a transform in Update should use deltaTime
does someone have a good video on making a self balancing ragdoll character all the videos I'm finding either don't help me or is not what I'm looking for
From when I made something similar, there really isnt a good video. It's called an active ragdoll, thatll help narrow down your search. But these require a LOT of fine tuning to get it working how you want. If you can avoid making an active ragdoll, then do so. If it's your games main hook, then goodluck because the videos you've found are likely the ones I've seen too.
The general steps are to have an animated version of the player, then your ragdoll tries to copy the rotations. Movement likely would just be with AddForce
mhm ok I'll work on other stuff then, thank you
If you do specifically need to use an active ragdoll, I can try to advise more on it. If you just need something that can ragdoll then what I said a bit above about enabling the ragdoll is a lot better. No matter how much I fine tuned my ragdoll, it never really looked clean with its movement. Theres a good reason active ragdolls arent in many games as the main character. Sometimes they are just animation driven, which I feel is no longer an active ragdoll because it wouldnt respond to forces then
ah ok, I'm going for like a simple Party game like Gang beast or Party Animals
Those games may look simple due to the goofiness, but trust me they are really difficult to make
From my experience as well, an active ragdoll is an absolute nightmare in multiplayer. I abandoned that project I was working on
mhm ok, still wanna try though even if it might be hard I still wanna try even if I have to ditch the ragdoll idea
Without the ragdoll part it is a lot easier, but no longer the same game. Still best of luck in it
Thank you again, you've been so much help
could someone drop me link of unity networking discord server?
it's pinned in #archived-networking
thank you
Not a lot of resources out there, it takes a lot of tweaking and figuring thing out yourself.
What helped me was these methods for setting a ConfigurableJoint's target rotation: https://gist.github.com/mstevenson/7b85893e8caf5ca034e6
Be prepared for a lot of head scratching. It's definitely an advanced topic
As bawsi explained, the usual way is to have a normal animated rig and another rig that copies the rotations from the source bones to the joints. This is where the methods I linked become handy