#💻┃code-beginner
1 messages · Page 654 of 1
Oh yeah, it's getting offset pretty hard there
also another couple problems i have once were done with this
How about when just standing?
Yeah that looks good
i might have found a solution
so my playerobj is where the camera is tied too
for height things
and its also what the raycast is tied too
so if i raise it up, is should in also rais where the raycast spawn
wait not the player obj
While that would work for now, I don't think that would solve the problem forever
how do i toggle specific layers from the camera from a script?
i have special effects that are under specific layers (fx a on layer 1, fx b on layer 2 etc)
i want a script that can toggle these effects on and off, how do i do that?
Something's coming to mind. Click the object when standing and when sliding
Show images for both
kk
Yeah, so you see right there? The transform position is at the bottom of the standing guy, and, well in nowhere land when sliding
yeah
I think there's a button you can click to change that, i forget what
the raycast should be spawning from the same spot no matter what right?
Ah ok, so look to the far left from where you clicked gizmos, across the screen basically
You'll see something saying "pivot"
Click it, and switch to center
yeah
Show images?
pivot
You switched it to center right?
Can I see your character hierarchy?
Show me the inspector side of "Player"
Show me the inspector side of "PlayerObj"
Hm ok, let's clean this up a bit
First things first, make sure the scene is saved
In case you want to try something else later
saved
i cant really get rid of any of the childs, as they are used in the Camera holder and player cam scripts
it avoids prolbems when the camera is directly attached to the player itself
Keep in mind that you may run into some errors and stuff as we do this depending on how you got your scripts set up. Ignore for now, until we get done
On Player, remove the capsule mesh filter and rigidbody
Reset its transform > right click transform > reset
done
doone
Any errors as of right now?
no
ran it got an error
MissingComponentException: There is no 'Rigidbody' attached to the "Player" game object, but a script is trying to access it.
Just to make sure this lands right, make rb public
can you wait like 45 min?
i need to go take care of somthing
i can @ you when back if your fine with that
replying so it doesnt get drowned
^ That I sadly don't know how to do, but I hope someone manages to help you!
yeah its ok im just leaving it here so someone picks it up lol
yeah but how do i do that via script?
like i can change it through script but i would have to give it an entire list of layers, i just want a method to toggle a specific layer
u could do bitshifting and stuff but me personally im bad at that..
so i'd just have a reference to couple of layermasks set up the way i want..
and just change out the entire mask w/ those layermasks
yeah but i have several layers that i want to be independently toggleable
ya, then u'd want to do the bitshifting stuff
im just telling u how I would handle it
im bad at that othe stuff.. sooo u'd need someone else to chime in
what is bitshifting
i dont trust ai
its Google's Overview.. it just uses all the sources from the search query..
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=uDYE3RFMNzk
Let's look at Layers and Bitmasks to see how they work. We can manipulate Physics interactions and what a Camera sees.
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials htt...
here
thats better thanks
the sources came from UnityDiscussions
ya, i dont trust AI either.. (coding with it).. but for search engine queries.. its literally using the results it finds and just giving u overview
anyway.. best of luck with the bitshifting 🍀
thanks
i'm going for pixel perfect movement but the players box collider keeps passing though walls only going up. I'm using rule tiles, should I just trash this project and start something new?
A tool for sharing your source code with the world!
your code is moving objects in ways that don't respect collisions
try setting Rigidbody velocity
also make sure your colliders and Rigidbodies are configured properly
i'm going for pixel perfect movement but the players box collider keeps passing though walls only going up.
(not kinematic, not triggers)
you said that already
are uyopui just NOT allowed to use colliders if you want a pixel game?
Who said that?
your code is moving objects in ways that don't respect collisions
try setting Rigidbody velocity
i am trying for pixel perfect movement
yes, that's what I wrote
nothing there says you can't use colliders
so why. isn't. it.working jsut one way?
Because you are moving your objects in ways that bypass collisions
like I said
_boxCol.transform.position = Vector3.MoveTowards(_boxCol.transform.position, targetPos, _speed * Time.deltaTime);
You are directly moving the Transform
you can't do that
if you want collisions
MovePosition also doesn't respect collisions:
_rigidbody.MovePosition(_boxCol.transform.position);```
ok. HOW do i wnat collsiions in a pixle art game wher i want pixle perfectt collsions
Well it really depends how the game works
is it like Pokemon where you can only move on a grid?
yes
then there's no need for colliders at all
You just need to keep track of which grid positions are walkable and which aren't walkable
and don't allow the player to walk to any non-walkable coordinates
ok, is there any resources for adding that to rule tiles?
no physics components at all
rule tiles are for graphics
tilemaps are for graphics
you got a youtuber that does this?
no
My best solution is having an if statement for the x value and nest another one for the y value
so what do i do? trash this whole project and find SOMEONE that can code this basci fuckign game correctly?
!learn how to code
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ya no one in this discord CAN apparently
most people on this discord can code their own game, consider it a privilege to get any help at all.. Don't feel entitled to it though
@waxen adder
plenty
back
clearly you cant code it properly so probably yes
if people are trying to help and you're the problem dont be rude lmao
so it doesnt get drowend again
oop
nvm
lol thanks but u dont have to do it, someone gave me bitshifting as a solution and im studying that
just noticed
This may be a bit stupid but couldnt you also just disable and enable its parent?
@waxen adder what if i just cast a seprate raycast when sliding?
rofl, no people are talking down to me 'why did you do it like this? this is wrong' i havent gotten any help ive been fucked by egos]
sure, thanks. sen most of theses allready
i sorta fixed it now i have other problems
of course right?
Can I search for script references on the editor?
Like "is there any object currently using this script?"
If your ide(at least visual studio but I think vsc as well) is configured correctly, it should show the references in the editor above your class definition
Oh, right, it does. Does that effect prefabs or only in scene?
I'm not sure. I'd assume it would list both prefabs and scenes.
There might be an option in the editor itself too, though I don't remember for sure.
So i'm new and working on my first game, Having an issue with raycasting, I followed a tutorial from someone online (Probably not the best idea) but that's how we learn right?
I'm having this very specific issue with it, As you can see it works flawless, Unless. I look at the object, and slowly back up without moving off the object lol. Super weird.
(can share code if needed)
Do share the code.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
Thanks! hopefully that worked
That's the Interactor script
Then each object that i want interactable just has a
public void Interact()
And
public class clipboardinteract : MonoBehaviour, IInteractable
(The interactor script lives on the main camera) from the unity assets first person controller)
I'd assume that you get an error in the console, right?
nothing shows to console as far as i'm aware
let me quickly check
nope console is clean
Aah, actually nvm. The issue is that you only disable the text when there is a hit
You need to handle a case where the raycast does not hit anything at all
I dont fully understand c# yet obviously but
isnt that whats happening here? with the else
in the vid you can see, if i move to the left or right of the object, the text vanishes fine as it should
It's only when I keep it in my direct line of sight, Back up SLOWLY, get behind the range of 3 while still looking at it, it doesnt remove itself
This else condition runs when the if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj) is false. So, whenever you are pointing at something that has no IInteractable component on it
You're only handling the case when you hit something that doesn't have the interactable component on it
You're not handling the case where you didn't hit anything at all
Ohhh
In this case 'air'
Like when i'm backing up i'm hitting nothing
I'm tryna think of the logic of how this would work then
Not sure if it would be something like 'null or 'void'
Like what is 'nothing' in this instance?
You appear to be changing the name you're assiging a variable to
which can be literally anything you want
Oh wait
Honestly, if you're following a tutorial, they should have it covered. Unless it's a very bad tutorial
Yeah it didnt cover it and I forgot which one it was now I kinda shot myself in the foot
In this video I go over the creation of a flexible interaction system in Unity3D.
Join my Discord! ► https://discord.gg/jrRJgfBz2y
How to Make Player Movement ► https://youtu.be/TOPj3uHZgQk
Extra Resources ►
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keyw...
Found it
Ok, look at the raycast documentation and investigate what happens if it doesn't hit anything.
Ok, well this tutorial kinda assumes that you have the basics of coding and know about all the "components" and concepts mentioned in it.
Why are you looking at the forums. Why are you not looking at the documentation as I suggested?
had a look through and seemed to have fixed it with this
It's weird because I assumed the 'else' would do exactly what the if line below it does
because it's the else from the original if
the undefined state is here
you have an else if you hit something and it wasn't an interactable
but not an else if you didn't hit something
Ohhhh
Thanks so much, it's fixed, I thought something wasn't right, I read the docs and it was saying what I THOUGHT my code was doing, thanks again!
no worries
not ideal in all cases but a suggestion here to get you thinking is if this is in update or something you can simplify the logic by just disabling it first unconditionally
eg.
MyInteractFunction()
interactText.setactive(false)
if (various stuff)
interactText.SetActive(true)
Yeah, It's funny because, I have worked with python and java and I'm not sure why I didnt see that
Must be brain tired
sometimes it just be like that
yo is copy and pasting a movement script a bad thing as a beginner?
Yes. You should understand how it works first. What each line does exactly and the syntax behind it.
Howdy anybody know what a 'script' is in this instance?
It's hard to explain one moment
You are supposed to write the actual type you are trying to reference
the class name for example
not "Script"
Every time you write a MonoBehaviour class you are defining a type of component that can go on a GameObject
then you would write PlayerInput as the type
Thanks again
Slight issue with cursor when pausing
I have a script when my game starts that disabled the cursor (which works great)
however when I pause I need to show the cursor
and then hide it when unpause
What happens is when I press escape to pause (in game view) this pulls me out of focus of the game, So i cant tell if the cursor actually appears. and then when I click back in, I dont have a cursor, but void Pause has 100% been ran
For testing in the editor usually you want to bind things to a different key other than escape, since the Unity Editor uses that key for taking focus out of the game window
Good idea i'll try that real quick 😄
Also, I would think most likely you don't want Cursor.visible but rather this: Most likely you want https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Cursor-lockState.html
Doesnt that just freeze it in place?
Oh nvm
i cant read
hmm thats interesting
on start i set
Cursor.lockState = CursorLockMode.Confined;
but i still have a moveable cursor in game
confined means you have a moveable cursor, it just can't leave the game window
you want Locked generally for a first person game
This is so perfect. Yeah with the way I was going to do it, it would have been like tabbing out of the game with the mouse moving out the window
but now it's confined on pause
Thanks sm
Is there really no better way of doing this when calling a method from a button?
you could add the listeners dynamically. e.g.
public Button[] myButtons;
void SetupListeners() {
for (int i = 0; i < myButtons.Length; i++) {
int temp = i; // this is important, don't neglect this
myButtons[i].onClick.AddListener(() => AddFunction(temp));
}
}```
but if you want to do it in the inspector you either have different functions or you pass the int parameter in in the inspector
[SerializeField] private int commandId
public void CallCommand()
{
commands[commandId];
}```
that works too - the buttons would subscribe the onClick to that function onthemselves^
I am not quite understanding this. Is the last line just adding a listener to call that specific method with the value fo the position of the button on the array?
And this I am guessing I would need to have a way to tell which button it's being hovered or clicked over for that to work
the idea would be each button has its own instance w number but i'd probably go with Praetors suggestion
it's adding a listener to a specific button that calls AddFunction() with the appropriate integer parameter
Mmm, my grasp on eventListeners is like null, aren't button on themselves eventListeners already?
I'm not sure what you mean by that
We're talking about listeners for when the button is clicked.
Isn't that what you're interested in?
AddListener does the same thing that you do in the inspector OnClick but in code
it links a method to the event "OnClick"
Yes, but I didn't even knew you could pass parameters with eventListeners if you set them through code instead of setting them on the editor with the OnClick event
its just a UnityEvent , in the inspector is the same you can pass or link dynamic values
So I were to run that on editor, would that show in the methods called by the Onclick?
not sure what you mean
If I do AddListener on code and run that on editor to add a listener to a particular button and pass it a parameter would it show here?
no
no this is strictly for the inspector
Many, many things. Volume? Do you have something to hear it? Are you sure you are playing it?
yes and if I tick for it to play on awake it works but the code doesn't for whatever reason
Do you have an audio listener in the scene?
Is it anywhere near the audio source?
Do you have sound enabled in your game view?
Oh also when and where in your code are you calling Play?
Are you doing it in Update?
I venture to say you are destroying the "gem" on pickup, thus destroying the audio source and stopping it inmediatly
oh that too^^
Create an emtpy prefab holding the sound and destroy it after a few seconds
Not the most optimal, but the simplest
Or use AudioSource.PlayClipAtPoint
And is there any particular reason to store the i on a temp here??
yes, to avoid lambda variable capture
which would make this not work properly
without that, all of the buttons would use the highest number in the array when you clicked them
because that's the final value the i variable has.
Mmmm, pretty sure I have it used it wrong some times before then
I use the i a bunch of times for final values on these
it depends what you're doing. This is a very specific case involving creating a lambda in the loop that makes it necessary
Now that I thinking about it, for how it's setup now, those buttons can be destroyed and created a bunch of times, would I have to remove the previous listeners or it's fine?
you wouldn't have to remove the listeners
does anyone know why does it define infinity? i just put an "Random.Range(-15f, 15f)" as for the Y axis
code in question:
wrong script
The error tells you where to look - Move_Pipes.cs, line 20
Also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh thx
public class Move_Pipes : MonoBehaviour
{
public float MoveSpeed = 5f;
public float Dead_Zone = -45f;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.x < Dead_Zone)
{
Destroy(gameObject);
}
transform.position = transform.position + new Vector3(-1 * MoveSpeed * Time.deltaTime, transform.position.y, 0);
}
}```
here is the right script:
you're adding transform.position.y to itself every single frame
it's going to get very large, very fast
hence the infinity
if you don't want to change the y position, you would add 0 to the y
like you are doing with z
z dosent change, but Y has to stay as it was creaated
so if i set 0 it wont change?
anything + 0 is the thing you started with
notice this is a vector you are ADDING to the position
you are not SETTING the position to this vector
pay careful attention to the code.
inside a prefab i can reference each object?
i mean, i know you can't reference a prefab as different objects/prefabs, but one children of a prefab can reference it sibling?
i mean cuz i want to make an Enemy that throws projectiles at you, and if one touches you it TPs to you (like an Ender Perl, huh). So my plan was just referencing to the Enemy and changing it Transform.Position to the Player's Transform.Position and thats it, and it would be A LOT easier if it were done using referencing, u know the
[Serialized] Privated Gameobject Enemyname;
thing
yes, you can drag and drop to reference objects within the prefab
nice, thanks :3
I would recommend using a Transform reference here directly, not GameObject
works now thx 👍 😀
oh makes sense
well thanks :3
how can i fix this? it says it's inaccessible because of "protection level"
public Ui_Manager manager;
void Start()
{
manager = GameObject.FindGameObjectWithTag("Logic").GetComponent<Ui_Manager>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D collision)
{
manager.AddScore();
}
you should really be more specific and provide all the info when you ask a question. I'm going to guess you're talking about the manager.AddScore(); line. Presumably the AddScore(); method in UI_Manager is private. You need to make it public if you want other scripts to be able to call it.
yeah sorry about it, and yes, the method is public, other script:
public Text UI_Score;
public int score = 0;
void Start()
{
UI_Score.text = score.ToString();
}
// Update is called once per frame
void Update()
{
}
void RefreshScore()
{
UI_Score.text = score.ToString();
}
public void AddScore()
{
score++;
RefreshScore();
}
you really need to provide the full error message you are getting with your question then
because with the code as you shared it, you wouldn't get that error
Assets\Scripts\ScoreTrigger.cs(20,17): error CS0122: 'Ui_Manager.AddScore()' is inaccessible due to its protection level
Looks like you maybe forgot to save your changes to the Ui_Manager script.
fixed thx 😀
Should I worry much about doing this instead of adding a simple int counter on something that happens relatively frequently or it's fine?
The components get added from outside, but I am trying to not add variables that are redundant cause I am getting confused enough already lol
What kind of counter? To replace what? And how? It's not entirely clear just from looking at the code.
A counter that basically goes ++ when adding component from outside and -- when removing it
What's the purpose of it? I don't see how it's related to the shared code
I am getting the amount of components of the type command on an object, since they are meant to be capped, so whenver I add one I check how many it has already
you could have that component register itself with some kind of central manager component which would/could keep track of the number that have registered
Overall, using GetComponents every time is not ideal
Yeah, basically the counter I was referring to, and the optimal choice, the question is how bad it's to let it as it is
if you're doing this often, it can be very bad
GetComponents<> returns a freshly allocated array
Bad in terms of what? Performance? Readability?
so that could be a ton of garbage collection
Performance, in readability it's just using a method over a variable
As Praetor mentioned, it's not great, but only you can tell if it's significant enough in the context of your game.
You could expect it to happen once each 1-2 secs if they are spamming it
Kk, should be okeish then
Mmmm.... What am I messing up here? I never got these before
Seems like an unity editor bug, try restarting
Okay, so the error was that I am trying to add items from the top list to the bottom one 1 by 1 without ever removing the top one since, it's a reference. And it does so, but... beggining from the second item, they get.... removed from the original list? How can I even be doing that? It's trying to fins stuff that does no longer exists, that was the error
Im kinda struggling with buffs and combo triggers.
Lets say i have 4 heroes. Hero 1 has a passive skill that says he gets healed by 5 if another hero deals a critical strike.
How would i implement this? Is there a way to make that skill listen for crits?
perhaps an observer pattern
Will look into it, thanks!
yall, when i bake in navmesh surface, it doesnt show me what i baked, usually there is a blue highlighted area what i baked, but i cant see it rn, any ideas?
i just had gizmos off...
Will remember that for my own navmesh
How do I rotate something over time in eulers? I just can't do it
I tried 500 different methods and none of them work
its quite easy so no idea what you were doing
I want to rotate something by X degrees on just one of the axes
that's al
I can't do it
you need something like a coroutine to animate it from some rotation to another
or you use an animation
yes I have that
a coroutine
The newest method rotates me by 180 degrees which is an incorrect value
tried other methods, they either gave me no rotation or random rotations
Share your code so we can see what is wrong
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
randomTilt = Random.Range(40f, 65f);
Vector3 targetPosition = new Vector3(Camera.transform.localPosition.x, 0.59f, Camera.transform.localPosition.z);
float deltaZ = Mathf.DeltaAngle(Camera.transform.localEulerAngles.z, randomTilt);
Vector3 targetRotation = new Vector3(Camera.transform.localEulerAngles.x, Camera.transform.localEulerAngles.x, deltaZ);
while ((Camera.transform.localPosition.y - 0.59f) > 0.002f && (Camera.transform.localEulerAngles.z - deltaZ) > 0.2f)
{
Camera.transform.localPosition = Vector3.MoveTowards(Camera.transform.localPosition, targetPosition, 0.1f * Time.deltaTime);
//Camera.transform.Rotate(Vector3.forward * (10f * Time.deltaTime), Space.Self);
Camera.transform.localRotation = Quaternion.Euler(Vector3.Lerp(Camera.transform.localEulerAngles, targetRotation, 1f * Time.deltaTime));
yield return null;
}
That's the relevant part
An example of linearly going from 1 rotation to another correctly
private IEnumerator Rotate(Vector3 from, Vector3 to)
{
Quaternion fromQuat = Quaternion.Euler(from);
Quaternion toQuat = Quaternion.Euler(to);
float t = 0f;
while (t < 1f)
{
t += Time.deltaTime;
transform.rotation = Quaternion.Lerp(fromQuat, toQuat, t);
yield return null;
}
}
Your rotation lerp is doing 1 * delta (for some reason) so its going to only slowly move to your target rotation and never reach it
well it doesn't do that
it just turns me pretty fast and reaches 179 for some reason
without delta angel, it worked but from the wrong side
oh and it sometimes rotates the wrong axis from reason
Camera.transform.localRotation = Quaternion.Euler(Vector3.Lerp(Camera.transform.localEulerAngles, targetRotation, 1f * Time.deltaTime));
This is bad because your from rotation is the current rotation, not the original start when the anim began. And your lerp factor is delta time.
In my example, we keep the start rotation and end rotation constant and we lerp to the goal over 1 second.
Perhaps you want rotate torwards? https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
your lerp factor is still wrong though, it needs to go from 0 to 1 over the time frame you desire
doing Lerp(5, 10, Time.deltaTime) for example each frame will just give the same ish result cus delta time is gonna be like 0.016
I would use rotatetowards if I knew how to express a vector 3 axis as a quaternion. Does Quaternion.Euler work with that method?
yes
one question is making a lot of function for like the most things like Movement() and CheckForGround() exc
good or bad?
neither
functions are generally for 2 things, reducing repeated code, and separating out independant subsections of complex code
(aside from providing functions for other classes or actions)
so if your function doesn't fall into those categories, it may be unnecessary; but that doesn't make it automatically bad
okay thx
Of course. It uses quaternions so you can make a quaternion from euler angles.
Rotations are always quaternions internally and euler angles are just a nice form for us humans to read.
now unity freezes
Quaternion targetRotation = Quaternion.Euler(0, 0, randomTilt);
while ((Camera.transform.localPosition.y - 0.59f) > 0.002f && (Quaternion.Angle(Camera.transform.localRotation , targetRotation) > 0.1f));
{
Camera.transform.localPosition = Vector3.MoveTowards(Camera.transform.localPosition, targetPosition, 0.1f * Time.deltaTime);
//Camera.transform.Rotate(Vector3.forward * (10f * Time.deltaTime), Space.Self);
//Camera.transform.localRotation = Quaternion.Euler(Vector3.Lerp(Camera.transform.localEulerAngles, targetRotation, 1f * Time.deltaTime));*/
Camera.transform.localRotation = Quaternion.RotateTowards(Camera.transform.localRotation, targetRotation, 1f * Time.deltaTime);
yield return null;
Infinite loop is a likely cause.
In my example I forgot to put the yield in btw
well I used yield
I didn't copy it
but there's a curly brace after null
OK I'm stupid
I put a semicolon after while
intellisense didn't even care about that one, the weirdo
ok fixed but it doesn't rotate
man I hate rotation
so unintuitive
does it highlight other errors?
no errors, nothing
but I'm back to not rotating now
i mean, if you put in an error, does it highlight that
yes
weird
it gave me a green squiggly underline
like it's not an error but incomplete
misunderstood the context or somethign
anyway, now fixed for good, my speed was far too low
but I still hate rotation
Hallo, I want to trigger an event when a specific message was send in my youtube livestream chat. Does anyone know how to use the Youtube Api and search for a specific word in a comment in Unity?
Hello I'm creating an RPG and I want to create a transition between my overworld and the battle scene. When the battle scene loads however I am unable to interact with buttons to perform commands. The battle starts when the player makes contact with the enemy. Can anyone help I'm really stuck
im not sure what that file is meant to be but thats useless to anyone
you need to post code
and the error
i think its the literal scene file 
but yes post !code and maybe some more details of what the scene looks like in your editor
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh sorry Im an extreme novice. this is what my battle scene looks like
Missing an event system when you change to this scene?
I have an event system for both my overworld and battle scene but not really sure what to do
can i post videos here
Yes
Heres the video. As you can see, when I try to interact with the buttons the mouse just dissapears.
I created a transition script but I don't know what else I can do.
Thanks for the help in advance. This is really draining me
The battle scene works perfectly when I play it from it's scene. It's just when it transitions
You have the mouse hidden in the overworld scene. It's going to stay that way unless you reveal it in the scene where you do want it visible
Alright How would I change it?
Well how do you hide it?
Nevermind I got it to work. Thank you so much
Though is there any reason as to why the screen goes darker when it transitions?
ugh why is code so... hard im not feeling my exp bar irl with it going up
xd
Is it from the UI? (disable the canvas to check) Have any post processing in the scenes? Light not as bright in this new scene?
Still not finding what the heck is going on here, there is no other way of removing a single item from a list without using one of the remove methods right?
wtf is a "lost"?
You must be doing something funky to cause those editor gui errors. Setting the value at an index in an array/list is valid
You can use Remove() to remove the first matching element in a list OR RemoveAt() to remove the specific index.
The list elements AFTER the element removed get moved up to fill the empty space.
Yeah, it's checking the command list to get the lowest id value on those, then looking for that value to get what command should be next to move into the active commands list, then it adds it to the active commands, but I am somehow removing item from the command list when it shouldn't be the case, that list should never be modified
Is this in play mode or edit mode?
I was actually trying to make the command list readonly but I am too dumb to get the right declaration for that I guess lol
List<int> myList = new(){1, 2, 3};
public IReadOnlyList<int> readOnlyList => myList;
Use a debugger to check what your code is really doing to these lists as you should not 100% rely on the inspector to check everything happening
Yeah, I have gone throught where the code os going a bunch of times and added logs, but... I don't see anything that could remove items from the list with the methods I am calling
No not with logs, with a debugger: https://unity.huh.how/debugging/debugger
The debugger is a tool that halts code execution. Values can be inspected, lines of code can be stepped over, and sometimes even modified. This does not require recompiling your code, or exiting Play Mode.
You will put a break point where this process begins and step though and check what is actually happening
instead of shit logs and guessing afterwards wtf is wrong 🙃
Mmmm... I guess I would place a breakpoint on each execution, but... I don't think I'll be able to catch anything with that either
I think I am calling something else, but not sure how, or what
a breakpoint when hit will pause execution and from there you can step forward a line manually and inspect stuff. You can then "Continue" to unpause execution and go back to normal
You should share your current code if you still need help with it
is this a good idea for multiple objects
sometimes objects with the script attached don't work
This is quite unreliable. You should query input in update.
did, same issue
i think it has to do with the collider
Possibly. I'd just use a raycast on your player controller. Way more reliable and easier to debug.
yeah it was a collider i forgot to remove, i'm already using raycast for a few different things so i'm gonna avoid it
https://paste.mod.gg/ydowtmdzcclz/0
Why can't I find any of my dragFuel methods here?
A tool for sharing your source code with the world!
I don't have any compiler errors
unity events can't target methods that have structs as arguments
Made a button on a pause menu to go back to the menu
public void OnStart()
{
SceneManager.LoadScene("menu");
}
It works, Switches to menu, But when I then go back to the game (aka start the main game scene again) my character controller cannot move? I can look around with the mouse, but not move around with WASD, any ideas?
To start the game in the main menu I have
public void OnStart()
{
SceneManager.LoadScene("main");
}
which character controller are you using?
error CS1061: 'PlayerInput.OnFootActions' does not contain a definition for 'Look' and no accessible extension method 'Look' accepting a first argument of type 'PlayerInput.OnFootActions' could be found (are you missing a using directive or an assembly reference?)
I followed this youtube tutorial https://www.youtube.com/watch?v=rJqP5EesxLk&list=PLGUw8UNswJEOv8c5ZcoHarbON6mIEUFBC and I cant seem to find out whats wrong with my code
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
The starterassets unity one, I'm uploading a video real quick to show you whats happening exactly one moment
here we go
At the end i cannot move at all just with the mouse
I need help fixing this compiler error
I'm an idiot.. my pause menu sets time to 0.. but then if you click return to menu it leaves the time at 0 lol
Thats why i cant move
(fixed)
hi! i needed an quick help, i wanted an object to rotate around an empty object i made, and for it i used the "transform.rotateAround" function, i put the transform position of the other object in the 1'st paremeter and in the second i up "Vector3.up" and the third as "20 * Time.deltaTime", i started the game and the object suposed to rotate around the middle one disapiers.
Script:
public GameObject Middle;
// Start being used as test
void Start()
{
transform.RotateAround(Middle.transform.position, Vector3.up, 20 * Time.deltaTime);
}
Screenshots:
The docs say:
Rotates the transform about axis passing through point in world coordinates by angle degrees.
i used the code the docs put
yours isn't in update though
they're also rotating around the 3d world's Y axis
does that make sense for your game?
oh
actually not
im trying to build an copy of the tap game
it rotates and you have to tap on an ball that apears randomly
but even when the game is not running the sprite dosent show up
the red one
maybe an render issue?
fixed it
camera Z axis was 0
put it on -10 and it got back to normal
Urgh goofed up my project
Ignore that wrong channel
Is there a channel for
'fixing unity things'
Not code but like... to do with URP etc
also finish a thought before sending a message, no need to spread a single thought across 3 messages
Does Anybody maybe know how to fix my enemy, so that he patrols a area and doesn't just walk in one direction all the time?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
also get your !IDE configured 👇
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
• :question: Other/None
Ok so
Im just trying to make a scoring system for when a wave a blocks gets past the player, count up by 1
i clone a whole bunch of block projectiles, so i would need a reference to those blocks to get their transform so i can see if they have gone low enough to count as a passed wave
the block is a prefab
can someone help me out with a vr horror game?
what do you need help with
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
configure your ide
anyways you should probably decentralize it a bit; step away from the code and think about design
im aware theres more ways to deal with this issue but i kind of want to know what the issue with my current approach is
Heres the block code
please share your !code properly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
I used Debug.Log and waveNum does increase as the waves fall
using UnityEngine;
public class Block : MonoBehaviour
{
public int waveNum;
void Start()
{
GetComponent<Rigidbody2D>().gravityScale += Time.timeSinceLevelLoad / 15f;
}
// Update is called once per frame
void Update()
{
if (transform.position.y < -2)
{
waveNum++;
Destroy(gameObject);
}
}
}
Heres the Block code
there should be a single "score" counter, that's correct as is - score should be centralized, there should only be 1 central score
but since there are multiple blocks that are created dynamically, that shouldn't be centralized; each block should be able to know when it's passed the threshold (perhaps passing that into a script on the prefab) and then just inform the centralized score that something should change
so the block should get a reference to the wavespawner, telling the wavespawner to increase score by 1 instead?
blockClone doesn't magically know about the cloned objects, it's just the original. the original doesn't change since it's not in the scene (hopefully)
something like that, yeah
I did this at first, i agree its the better approach and had another issue
Let me send that too
Yea thats what i was thinking to why it wouldn't work
and dragging into the scene wouldn't do anything cause im still cloning it
Give me 1 minute to get my other approach
Ok so i tried referening the score TextMesh from the BlockSpawner
im using an old version of gtag as a base, trying to make an entity that goes toward the player, no anims, just flying, and will do a jumpscare and close the game after. its gonna be a rare 1/100 every hour chance
the blockspawner would increase the waveNum variable, and the Textmseh would get that variable
however in the unity inspector, everytime I dragged in my Score textmesh on the canvas
it did not recognize it and said type mismatch
which confused me cause in blockspawner i have public Score waveNum
you mightve just used the wrong type yeah
so dragging in the score textmesh should be the same type??
im confused
I was too thats why i did other crappy method
"the score textmesh" as in, the object that has.. just the textmesh?
yea just this score
and does that gameobject have the Score script..?
yes
sometimes i would delete on the blockspanwer inspector, and i was able to drag the score script successfully
but i would run and it would change to the type mismatch
are you currently back to that version of code
(btw, why are you adding to the gravity scale like that? you're adding snap, the 4th derivative of time)
Idk lol im new
No, i am trying a 3rd approach that seems way more promising, but whether this works or not, im going to retype that other issue in like 3-4 minutes
cause i still want to know why that wasn't working
Ah
this 3rd approach is having the exact same issue
so this works for demonstration too
make sure you've saved and recompiled all scripts
Yep i have
alright sending a few things rn
using UnityEngine;
public class Block : MonoBehaviour
{
public Score scoring;
void Start()
{
GetComponent<Rigidbody2D>().gravityScale += Time.timeSinceLevelLoad / 15f;
}
// Update is called once per frame
void Update()
{
if (transform.position.y < -2)
{
scoring.IncreaseScore();
Destroy(gameObject);
}
}
}
using TMPro;
using UnityEngine;
public class Score : MonoBehaviour
{
public TextMeshProUGUI score;
public int currentScore;
//public BlockSpawner currentSpawner;
// Update is called once per frame
void Update()
{
score.text = currentScore.ToString();
if (currentScore < 0)
{
score.text = "0";
}
}
public void IncreaseScore()
{
currentScore++;
}
}
BlockSpawner script no longer relevant
This is where you can see the block prefab with its script in the inspector
I drag in my score Text mesh
Ah
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
thank you!
assign the Score in the BlockSpawner instead, and then assign that to the Blocks when you instantiate them
so prefabs can never reference something in the scene?
yeah, since prefabs exist outside scenes
makes sense
sorry that took so long, this isn't a super rare issue, i just haven't had to help anyone with this issue yet lol
nah i really really appreciate it and i wanted to get all my approaches out there too
so i could like fully understand this stuff
How is this failing just sometimes? I don't get it
The command that I am telling it remove is on the list 100%
It even happens if I use Clear() instead, how?
it looks like the error is because it's removed?
Yeah, but the error happens, precisely when it is NOT
try adding a print after the Remove call?
Like it removes it properly when it works, but not when failing
????? How?
It's literally passing data between 2 lists, like....
Pretty sure it's me using a loop wrong somewhere, but I am unable to find it
Ive never seen these serialization errors, perhaps you need to reset the component and re assign stuff and see if it helps
something is messed up, runtime changes should be just fine
Or... just stop having the active list serialized
Why would it showing in the inspector cause issues?
Isn't that what serialized is for?
I presume the issue is you remove an element but the inspector still shows it. The error logged also mentions this list and element 0 so its surely related.
So a potential solution is to use [NonSerialized] so its not fucked with
and activeCommands is just a List?
the errors there aren't directly from list operations, it's from what the editor is trying to do after the list operations
I don't think the editor should be trying to do anything, no
me neither, i agree it's weird
thats why i think the component needs a reset (via ... menu) or remove and re add it
Could it be that I am destroying the object before removing it from the list sometimes somehow?
Cause shouldn't be the case
Removed the component, added it back in, didn't seem to work, I just edited a freaking log string after that and now it doesn't show..... Aaaah, why??? I am so confused!!
editor issues be like
uhm this is pretty weird
public void Test()
{
Testing = !Testing;
Debug.Log($"Testing is {Testing}");
if(!Testing)
{
StopTest();
}
else
{
StartCoroutine(StartTest());
}
}
private void StopTest()
{
Debug.Log("Ended Testing");
}
And the result of debug.log is!! HUH?
consider printing the value of Testing in your StopTest method. also check the stack trace
ah wait the corontine was waiting for microphone to get stopped so that ui stops too
got me scared lol
Could this be removing from the commands list on way a that I do not understand?
Cause the idea was to create a copy of it to get which ones are on the commands list but not on the inactive commands list
just started scripting today, would this work?
There is nothing on that script that could work, like you have, quite literally, not done a single command
i mean the header
Not as a comment and not with nothing below it
yeah i just wanted to see if it would show in unity
do you know any good tuts to help me learn
Pretty much anything you find on your first google search would work
cause a lot of the tuts i find just teach you to copy what they put and not actually learn
Go to Unity Learn, it's pretty decent to learn the basics
But, again, any youtube vid would do the trick
just watched a small tut, according to the tut this should work?
so when i boot my game up it will display hello in the console
it worked!!!! finally my first code that I made
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
cameraTransform = Camera.main.transform;
// Hides the mouse
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
// Enable interpolation for smoother visual movement
rb.interpolation = RigidbodyInterpolation.Interpolate;
}
void Update()
{
RotateCamera();
MyInput();
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
if (grounded)
rb.linearDamping = groundDrag;
else
rb.linearDamping = 0;
}
void FixedUpdate()
{
MovePlayer();
SpeedControl();
}
private void RotateCamera()
{
float horizontalInput = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate(0, horizontalInput, 0);
float verticalInput = -Input.GetAxis("Mouse Y") * mouseSensitivity;
targetVerticalRotation += verticalInput;
targetVerticalRotation = Mathf.Clamp(targetVerticalRotation, -90f, 90f);
// Smooth the vertical rotation using Lerp
verticalRotation = Mathf.Lerp(verticalRotation, targetVerticalRotation, Time.deltaTime * 10f);
cameraTransform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalinput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
// calculate movement direction
moveDirection = orientation.forward * verticalinput + orientation.right * horizontalInput;
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.linearVelocity = new Vector3(limitedVel.x, rb.linearVelocity.y, limitedVel.z);
}
}
anyone know why its so jittery? im still learning the components, statements and syntax for Unityengine, and It itself and I can figure out why its so jittery, i can send a ss of my player as well
Unity keeps giving me these errors but there is nothing wrong with the game, can anybody please tell me how to fix this?
Did you enable interpolation on your Rigidbody?
How is your camera moving?
wdym
hold on, what did i do to my code yesterday
gimme a second
now my player aint moving
what did i do 😭
oh, the camera is a child of the player
does anyone have an extra horror ai script? i cant seem to find any
got the strangest error ever going on rn
this is after attempting to this up
So heres my blockspawner
using UnityEngine;
using TMPro;
public class BlockSpawner : MonoBehaviour
{
public Transform[] spawnPoints;
public Block blockPrefab;
private float timeToSpawn = 2f;
public float timeBetweenWaves = 1f;
private Score scoreCounter;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Update()
{
if (Time.time >= timeToSpawn)
{
SpawnBlocks();
timeToSpawn = Time.time + timeBetweenWaves;
}
}
public void SpawnBlocks()
{
int randomIndex = Random.Range(0, spawnPoints.Length);
for (int i=0; i<spawnPoints.Length; i++)
{
if (randomIndex != i)
{
Block blockInstance = Instantiate(blockPrefab, spawnPoints[i].position, Quaternion.identity);
blockInstance.Initialise(scoreCounter);
}
}
}
}
Here's my block code
using UnityEngine;
public class Block : MonoBehaviour
{
private Score score;
void Start()
{
GetComponent<Rigidbody2D>().gravityScale += Time.timeSinceLevelLoad / 15f;
}
// Update is called once per frame
void Update()
{
if (transform.position.y < -2)
{
Destroy(gameObject);
}
}
public void Initialise(Score scoreCounter)
{
score = scoreCounter;
//score.IncreaseScore();
}
}
using TMPro;
using UnityEngine;
public class Score : MonoBehaviour
{
public TextMeshProUGUI score;
public int currentScore;
//public BlockSpawner currentSpawner;
// Update is called once per frame
void Update()
{
score.text = currentScore.ToString();
if (currentScore < 0)
{
score.text = "0";
}
}
public void IncreaseScore()
{
currentScore++;
}
}
and here my Score code
This shouldn't work, but i just wanted to get all the referencing setup properly
anyway... if you look at the commented code in the Block scrip
if i uncomment that... which should just run the IncreaseScore method, increasing that random integer by 1 for score
it literally causes my blocks to infinetly clone every frame and glitch out the whole game???
I have absolutely no idea whats going in, my code seems like it would just be increasing an integer meant for a text after Initialising
Non-looping animation firing twice
make sure you didn't put the block spawner script on the block itself for example
you see my script right? i dont think i have that at all
you don't think you have what at all?
the block spawner script on the block itself
can you show the prefab?
It doesn't clone infinetely unless i uncomment that one line
And i have no idea how that line could be related when its controlling an integer only used for the textmesh
collapse all the components so we can see them all
and show us which object we're actually looking at
my theory about the infinite spawning is this:
- You never assigned a value to your
scoreCountervariable in the BlockSpawner script - Therefore you are going to get a NullReferenceException in the Initialize function when you call
score.increaseScore(); - That means the
timeToSpawn = Time.time + timeBetweenWaves;line is never running - That means you will call SpawnBlocks every frame because the timer is never updated.
that's your issue
in fact I'm 100% certain
So my advice:
- Pay attention to your console window, it's telling you important errors you are ignoring.
should i make my scoreCounter variable public in blockspawner
I know the first bullet point is true because it's a private variable and never assigned in the code
if you wish to assign it in the inspector, yes it should be public or have [SerializeField]
it has no idea what Score to Initialize righT?
how do i fix this?
yes, you are passing it null reference
thank u haha
Spell MonoBehaviour properly
also you need to configure your IDE
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
😭 i didnt see that
you didn't see it because your IDE is not configured
get it configured immediately
ok
Random suggestion, you should put your scripts in a “Scripts” folder so its more organized. Just a suggestion.
Technically, you don't need to force rebuild ui. If you do you're probably doing something unnatural with it.
And if you do, calling it on the parent should be enough
I am adding stuff to the layout and it's not updating properly
I am calling the parent to update in cascade cause apparently it does not do that by default
Then you're probably having some contradicting setup. Like having a size fitter or something with a layout group
Many of those, yes
Well, then perhaps rethink this setup. They're not intended to be used together
Quite literally falls over without those
Falls over?
Transform curr = transform;
while (curr != null) {
if (curr is RectTransform rt) LayoutBuilder.BlahBlahBlah(rt);
curr = curr.parent;
}```
Hey privateIK isnt found and i imported System.Collections.Generic
using UnityEngine;
using System.Collections.Generic;
public class PlayerGunSelector : MonoBehaviour
{
[SerializeField]
private GunType Gun;
[SerializeField]
private Transform GunParent;
[SerializeField]
private List<GunScriptableObject> Guns;
[SerializeField]
private PlayerIK InverseKinematics;
}
Like these, it tells me I should not use them together, but if don't add the content Size Fitter it does not occupy any space on the layout and everything overlaps on it
What does "privateIK isnt found" mean?
Invserse Kinematics
Ok but what does that have to do with the code you posted
no i meant PlayerIK
Did you define that class?
What does System.Collections.Generic have to do with anything?
It certainly doesn't contain anything called PlayerIK
yea i see i fixed it
Canvas UI is pretty tricky to get something like this working. If I remember correctly, you'd need to have them on separate objects. The thing is that a layout group resizes the children to fit its own size, while a content size fitter resizes itself to fit the children, so it kinda creates a contradiction, since the UI system doesn't know what rule to follow.
Maybe someone in ui channel can guide you better on this, but having these components on the same object is definitely not a solution.
Not how it's intended to work, but works for me
Well, it forces you to do weird and unreliable stuff like forcing the UI to rebuild
It might have other issues and/or work differently on different platforms/in the build.
It's consistent if you tell the parent to be reloaded, it does always the same thing
But surely, I am using it wrong and should learn it better
When an enemy dies, check if it's the last one, and if it is, call next wave
I want it to be constant spawning
Well, then just call them each X seconds or make a pattern, or even make the intervals and quantity of enemies random, there is a bunch of ways
But what loop works best for that?
What are u ven asking there? Just drop it in update and make a timer
Well I need more control of it. Right now i'm trying to use a Enumerator but they spawn way to fast even tho I have a spawn interval
What control do you need
Where to spawn, how long to wait, making sure they don't spawn inside a object, etc
those all sound like separate concerns
Ensuring where they spawn and ensuring they have space to spawn is not related to what loop you would want to use
Fair, but still knowing the best for it would be nice
there is no "best" in general, it's going to boil down to your specific requirements and needs here.
The first step is figuring out how to express those requirements.
For example: "I want to spawn one enemy every 5 seconds"
Like, it depends 100% on the design of what kind of game you want to do and "a best loop" may not even exist, multiple are equally valid
Fair, but can someone help me why they are spawn in less then a second even with the delay that should be there? https://paste.ofcode.org/eKL3Zzznn9zNCmjCQtipfj
you can't just yield return a float in a coroutine
that will wait just one frame
you would need yield return new WaitForSeconds(SpawnInterval);
Hey it says i have an error while shooting my gun and i dont see any errors
everything here is set too
line 41 is ShootSytem.play();
gunscriptable object is the glock model
What do you mean you can't see any errors? It's right there
yea but doesnt make sense
What doesn't make sense about it? Something on line 41 is null but you're trying to use it anyway
classes are not models so no
So, ShootSystem is null
ill come back if i cant fix it
How could I remove interaction over a whole menu under a given condition?
Like remove the pointer events on X objects directly
for shootsystem its a particle system and i already added a value so i dont understand how could it be null and even if i do set for the shootsystem to work even if its null i get this error which i set up when the gun is not null
So, that error says that there's nothing in Guns that has a Type of Gun
So, what's in Guns
You could remove the GraphicsRaycaster from the canvas
That's what I was thinking, but I don't want all components in the canvas to be dissable just some parts of it
You could use a Canvas Group to toggle interactables off for an entire group
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/class-CanvasGroup.html
the gun scriptables
Oh, I see, may be tricky with scrolls tho
So there's nothing in that list that has the Type of whatever Gun is
i see i set it up wrong
dang ill have to write more lines of code to fix this issue
hello, i want to ask
the Container is just empty object
why when I click the object, nothing happens
the code is still empty
private void OnMouseDown() {
Debug.Log("Coin collected!");
}
I think you need an event system in the scene for OnMouseDown to work. And a physics raycaster as well probably.
You have to convert it to a Vector3 that has Z set to the Vector2's Y. Also note that multiplying the result of Random.insideUnitCircle with the position doesn't make much sense.
public Vector3 RandomPointInAnnulus(Vector3 origin, float minRadius, float maxRadius)
{
Vector2 randomDirection = Random.insideUnitCircle.normalized;
float randomDistance = Random.Range(minRadius, maxRadius);
Vector3 point = origin + new Vector3(randomDirection.x, 0, randomDirection.y) * randomDistance;
return point;
}
Why is that if you could explain more
Which part?
Why mutilplying it doesn't make sense
The object's current position doesn't have anything to do with generating a random direction so the result is nonsense
Imagine for example if the object is at (0, 0) then multiplying the direction with it would always result in (0, 0)
Yeah, that makes a lot more sense
so, i just only need to add new "event system" object and add the "physics raycaster" component inside it?
I think he means adding a physics raycaster to the player so it can tell when it's looking at the object
Or if it's the mouse, the mouse is over the coin
how do you paste code like this????
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
public class Program
{
public static void Main(string[] args)
{
System.Console.WriteLine("Hello, World!");
}
}
YUR
thank you
Yes
its still in planning stage, but i planned to save down input action mapping as json data , and reapply when user login or when its needed
if i gonna let users to customize their keybinds
this thing should be saved locally, not on server, waste of space
so does other player related stuff like setting preferences
Are you asking how this can be accomplished or?
is this design acceptable? or if we have a better approach plz share
especially on input system part
Saving to json would be fine and then loading it in, saving when the application is closing, loading when it starts
Hello, Is there a tutorial that introduces the very basics? I've followed along but I don't understand where is the entry point of the game?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yes I'm following one now, the roguelike but I don't get how the unity engine knows what classes govern what
what is the entry point, what monobehavior is, etc
Modifiers, like public, internal, private
It doesn't, that's up to you to decide overall
components
Yeah, gives access to unity functions like Start, Update, Awake, stuff like that
you'd probably have to ask more specific questions or theoretical examples to help get can understanding of what your looking for specifically here
Okay thank you, I'll try to come up with a more specific one
Okay so like: Right now, I have a PlayerCharacter gameobject, a BoardManager, and a GameManager which governs both the player and the board (via composition).
1st question: In the inspector tab for the GameManager class, do only player controller show up and board manager because they inherit from MonoBehavior? And TurnManager is just a c# class, carrying some data unrelated to Unity?
2nd: How does unity know which file is the entry point for my "game"? I could have multiple GameManager gameobjects, and how would it know which one to draw to the screen?
where do I just go to learn about this basic workflow stuff instead of following a guide to make a basic game and learn some of this on the side?
I think you're going about this all the wrong way
what is the correct way? sry im new
playercontroller and boardmanager show up because you assumably have them using the public accessor. If a field is marked as public or explicitly via [SerializeField] and supports serialization and inspector display Unity will show it in the inspector like that. This is supported by unity kind of on a case by case basis but supports a majority of types (a big outlier for example are dictionaries)
Unity doesn't know nor care about an entry point for your game. having a "GameManager" object is an interpretation you have made up which is fine but doesn't have any actual standing in the context of Unity. (also drawing to the screen is irrelevant in this question).
Anything deriving from MonoBehaviour recieves the Awake and Start call when they are first created and enabled for the first time. This is the most common entry point to start composing a system of your choosing. (but not the only way)
Okay so things that inherit from monobehavior will implicitly support inspector display? And I have to do it manually for c# classes?
TurnManager there was public, so this is the only difference
usually yeah. for base/poco classes you will need to explicitly mark the class with a [System.Serializable] attribute in order for Unity to show and serialize them. You may also need to mark the field using them with [SerializeReference] depending on your usecase and expectations
I forgot how but how do I get this Random.range to also work as a int for the if statment?
If your coming into Unity new with prior c# experience it may be worth trying to use MonoBehaviours as much as possible to get comfortable with the Unity workflow (but base/poco class usage is totally valid overall ofc)
Okay, thank you! that clears up my questions and yes I will try to use monobehaviors more to get used to it
no worries
a majority of people end up using some form of a singleton pattern to create those kind of gamemanagers and such
makes things a lot easier
can't you save the int as variable and call the variable instead?
How would I do that cause I want both Random.Range to equal the same
var randomInteger = Random.Range(0, Enemies.Length)
and whenever you need a new randomInteger, set the variable again when called
Well the same problem happens
What is the problem
I need the var to be a int not a Gameobject
This will result in an int
persumably that if you repeat call on while loops you should get a new number every tick the code was ran
This will result in a gameobject because you are taking a gameobject out of a list or something
@glossy crystal this is super generic but just a super duper rough example of using a singleton along with an objects awake call to get some form of workflow going
public class GameManager : MonoBehaviour
{
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
_instance = Object.FindFirstObjectByType<GameManager>();
return (_instance);
}
}
public List<MyContentExample> AllActiveContents { get; private set; } = new List<MyContentExample>();
public void RegisterContent(MyContentExample content)
{
//stuff with content
allActiveContents.Add(content);
}
}
public class MyContentExample : MonoBehaviour
{
private void Awake()
{
GameManager.Instance.RegisterContent(this);
}
}
What do you mean?
I'm not looking for anything
What do you want your code to do?
Never mind, I figured what I did wrong
sorry i was responding to this
lmfao sorry for the confusion mb
Partially my fault for not realizing you weren't the same person
🫠
thank you!
So I want the code to to a assigned number which equals a certain enemy. I want to use this number to select what enemies going the spawn and what how far they'll spawn compared to other as well later. Where i'll be setting different spawn times
Possibly due to your math, slideFriction might be going up rather than down and it moves you that way
So the problem I have now, is that I can't turn that int back into a gameObject. I need it to do both
my suggestion is to have some var randomness = Random.Range() to generate a random number in the range and call it every time you need to have a new number
then you can perserve the number for calculations but also get a new random number later
Just store both the GameObject and int, or just get it from the list again like you are already doing with the number
But how would I turn that number back into the array so I can get it
array[number]
That will return the object at index of number in the array
It's the same thing you are doing right now
Everything
I would hope you know the basics of doing things in unity, right?
I know everything that I tried before
if currentVelocity -= currentVelocity * (slideFriction * deltaTime) and slideFriction is positive and less than one, it should always output a lower number
Well you can't really go:
GameObject enemyToSpawn
You can go
(GameObject)enemyToSpawn however it's redundant since to convert to a GameObject, it would already need to be something similar, in which case you can just put enemyToSpawn
I know that but it doesn't exist in the curent context. So there is something that I need to put before it.
Well, I'm not very smart when it comes to math, so I won't be of much help spotting a mathematical issue aside from the possibly obvious factors, since it deals with a lot of math, #archived-code-general or #archived-code-advanced would be best as people in there likely know more than me
ight thanks
Also, remember to delete your post from in here if you are gonna ask in there as it's a recent post, just to prevent multiple answers, confusion, and such
Then it doesn't exist
Putting something before it, same issue, it won't exist
The variable doesn't exist
yea originally i asked in general but seems like no response so tried my luck here
Need to go over C# basics. Specifically over class fields.
darks advice is really weird ngl
the issue here is you want
GameObject enemyToSpawn = Enemies[randomInteger] not Enemies[randomInteger] = GameObject enemyToSpawn
the logic is the wrong way around
While that would be good, none of it will stick unless I put it to use. I have gone and done it. Most of the stuff I learned is in here
Well, you can go over it, then put it to use right as you are going over it
Code along with the basics, test it out, then continue
Well definitely not what I mentioned
And yeah, perhaps go over variable assignment as well
https://paste.mod.gg/cptmfzlsojip/0
idk how this is happening and im scared
A tool for sharing your source code with the world!
what is numOfDialogue set to
You probably have multiple copies of this script in the scene
i only have 2 and the other one is disabled
well i do have this
and show the full npc controller inspector + full npcdata inspector
hello! unsure if this would be a good place, i want to add like a model that goes under the road like a support bridge or beams maybe? any ideas?
thought maybe it would be coding
its not coding
but its not a parent so i dont know how it would affect anything
Anyway the solution here is basically to add more logging. Just do some basic to debugging that questions your assumptions
there is nothing in this conversation that would make it's parent/child relationship relevant
Im following a tutorial in youtube but I cant put CounterTopPoint into that script
Print all the information out including the name of the object, the array length, the value you're accessing, etc
[SerializeField] private Transform counterTopPoint;
I tried GameObject instead of Transform also
at the bottom of the script
ah, did not see that, apologies
can you show both screenshots of the inspectors
full
both npcs?
the npcdata in question and the npc controller
text controller
nitpicking but its weird that you have a NPC_Controller class referenced to as an npcData but it's not an issue
the script controls the npcs but it also stores the data within
looks like numofQDialogue is going to 2 for some reason
turns out i had referenced the wrong array - fixed, thank you for your help
youtube tutorials arent the best to start out with, try the !learn thingy unity has
to answer ur question tho, [SerializeField] private GameObject counterTopPoint; is correct, you probably just didnt save it
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
How can I post code blocks/files onto here? I'm having trouble saving and loading the position of the player character
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
I used paste.mod, Do i just post the link to it here?
A tool for sharing your source code with the world!
oh dear god
please please don't use playerprefs for save data, especially not like this. playerprefs isn't really meant for that despite the many tutorials that teach it as an easy way to save data
you should look into serializing to json and writing to a file instead of using playerprefs
Alright then I'll look it up thanks
oh and just so you are aware, quaternions are not angles in X,Y,Z with a 1 as the W
It's easy to convert to and from euler angles
Just don't mess with a quaternion thinking it's xyz in degrees cus it's not
Alright then
Example: transform.rotation = Quaternion.Euler(0,90,0);
it is instructions for posting code in this server
Got it👍
note how the instructions for correctly posting code do not include screenshots of your code
Okay👍
and make sure to follow the instructions for configuring vs code as having a configured IDE is a requirement for receiving help with your code here
I tried clicking on the links nut it doesnt take me anywhere🤔 What should i do?
wdym it doesn't take you anywhere?
So yk theres like links in the message
tried clicking it
doesnt bring me to anysite
that sounds like an issue with your stuff 🤷♂️ dunno what to tell you
😔 👍
Hello, I'm wondering why nothing shows up here, but I can still manually drag a prefab in from the projects tab and it works?
Unity shit
I have wondered the same but I think it doesn't work properly with monobehavious as technically the prefabs are of type game object
if you turn on the advanced selector it supports a lot of those unsupported cases iirc but needs time to bake/index your project compared to how instant the default one is
Hm I turned it on but still doesn't seem to show up, I have the filter for this, and my prefab has the required component, am I doing something wrong?
Indexing is still in progress.
It used to not even say the second part so you wouldn't know
And for some reason the default operation is to select the asset and not open which baffles me
I’m working on a beginner level game with the rollaball unity learn guide.
I got up to the point of where I’m baking a navmesh for the ground to work for the enemy agent object but it feels like it’s not loading at all. Any advice I could use to make it run faster or any settings I could be missing?
pls screenshot instead of using a phone
I'm having an issue where my configuration struct is assigned factory values in the unity editor, but in runtime it won't reference the actual factroy objects.
you sure this is a beginner issue lol
