#π»βcode-beginner
1 messages Β· Page 472 of 1

you dont really need async for something like this right?
Texture2D texture = new Texture2D(sourceImageInfo.imageWidth, sourceImageInfo.imageHeight, sourceImageInfo.textureFormat, false);
texture.LoadImage(File.ReadAllBytes(filePath));
texture.name = fileName;```
i would say 47 iterations
cuz i counted
@sour fulcrum just make sure you reference the instantiated settings SO so your UI will change the correct one . . .
ya im creating it via a property kind of like a singleton pattern
so any outside scripts will get the runtime one
public class ScriptableSetting<T> : ScriptableSetting
{
protected ScriptableSetting<T> RuntimeSettings
{
get
{
if (runtimeSetting == null)
CreateRuntimeCopy();
return (runtimeSetting as ScriptableSetting<T>);
}
}
[SerializeField] protected T _settingValue;
public T Value
{
get => RuntimeSettings._settingValue;
set => RuntimeSettings.SetValue(value);
}
protected void SetValue(T newValue)
{
T oldValue = RuntimeSettings._settingValue;
RuntimeSettings._settingValue = newValue;
OnValueChanged.Invoke((oldValue, newValue));
OnChanged.Invoke();
}
public ExtendedEvent<(T oldValue, T newValue)> OnValueChanged = new ExtendedEvent<(T oldValue, T newValue)>();
}
public class ScriptableSetting : ScriptableObject
{
public ExtendedEvent OnChanged = new ExtendedEvent();
[SerializeField] protected ScriptableSetting runtimeSetting;
protected void CreateRuntimeCopy()
{
runtimeSetting = Instantiate(this);
}
}
abit of my super cursed code
oh neat it's kinda working
nice . . .
Guys is it possible to make graphics like this in unity?
https://www.instagram.com/p/C706AyvI2bf/?img_index=3 IF so what kind of stuff can i research?
Unity is not modeling software so no. You can make things like that in Blender for example and import to Unity
you can achieve a render like that using HDRP . . .
yes you can
but its better to do such stuff where its supported
i would suggest maya and blender
use version control, github
github?
thats for storing the project isnt it?
Any git. GitHub Desktop may be suitable, for example
isnt github a website
and what else do you consider a backup to be?
Yes. I am talking about GitHub Desktop
yeah but its like saying to store it in a usb drive, yeah i know but what do i store
and where are the files?
any unity github guide will go exactly through the steps and what to actually commit
do you not know which folder you selected when you created the project?
Anyway the file location is directly underneath the project name in the hub
nah i always just keep everything in the default folder
it is
i just did that and i got some quick question
1: does it automatically update the github page or do i have to update it manually
2: and if no is there just a "update button" or do i have to tell it again which file to upload then overwrite the old file?
The GitHub page is updated when you click on "Fetch origin"
oh ok
how often should i update it?
There is a number of non-fetched commits, which is non shown if is 0
When you're ready to publish your commit
Yes, since you can keep track of your commits and back up if something doesn't work
Hey guys I need to access a variable inside my playerBullet Script that is inside my PlayerBullet Prefab. But the bullet is just spawned around 5..10sec inside the game, but I need already the value to appear in the screen since start, but not being able to do it as it was not spawned yet and I cant get the value, any ideas?
what do you need it for? this sounds like you have something setup backwards
also nothings stopping you from reading values from the prefab itself
like show on the screen.. like player damage.. so when game starts the damage will already show on the screen of the bullet
how do I acess the value inside the prefab already even without being spawned?
the exact same way you access it when it is spawned. although needing to do this sounds very questionable still. Could you not just spawn the player in and enable it around 5-10 seconds rather than spawn it at that time? Would save you from having to reference the prefab then the spawned object if these numbers change
I can but them in the screen it will be updated only after 5..10 sec and that is ugly..
i have no clue what that means. Nothing i suggested visually changes anything
Game starts, you have in the screen a text saying. Player damage: 2
that number 2 I can get only when the bullet spawns that is the prob
Well as I said above, no you are not limited to this. You can get it from the prefab.
But again this seems very backwards. so I suggest you either spawn the object earlier or have this damage number exist elsewhere
Ok, I will make it elsewhere. thank you π
I can put that script not only on playerbullet prefab but also on my player, is that gonna be bad? player is always spawned on the scene..
i have a public static gameobject array , why it doesnt show up on editor ? even with [SerializeField]
because Unity does not serialize static objects
oh i got you thanks
i have no clue what script you are talking about, so thats up to you to decide. if it isnt a hassle to get the value, and it makes sense to be on the player then sure
already fixed here ty ty
Issue: The time (in minutes) on package labels decreases by 2 every second instead of by 1. However, when the minute is at a number ending with 8 or 3 example (38 and 33), it decreases by 1 to 37 or 32, and then continues decreasing by 2 until it reaches 8 or 3, respectively.
Script: https://pastebin.com/mX06pqsY
i have 73k errors in 200 lines of code, this is the definition of pain
you should really add debugs and see whats happening specifically. also this doesnt make a whole lot of sense. the time in minutes decreases by 2? i only see you adding to it in update
tried debugging but idk how really any further, yea it decreases by 2 on the package label but ti should by 1. so 1 in game minute = 1 irl second
I have to ask, why are you not using a TimeSpan?
I followed a tutorial for day and night cycle and he included the time manger in it so I used his
So I just built upon it
i see no debugs in your code. but also i have no clue what value you're talking about. Do you mean timeLeft since thats the only thing related getting set to the label text
Yes time left, It counts down
And thats what decrements by 2 instead of 1 every second
that seems like its just using the hours, which would imply its going down by 2 hours every second
you will probably find solving one basic structural one with reduce that considerably. So double check your code structure very carefully
i tried and now i have 162k errors π
do you know what I mean by 'code structure'?
brackets and stuff like that?
exactly
add debugs for, (or some way to see), elapsedMinutes and totalElapsedTimeInHours
Check if the minutes there are correct. If they are, then its some issue with your delivery time.
If they arent, then check the equation in line 7.
Also if you attach the debugger, you can just see all of these values and use breakpoints to run the game line by line
it should be pretty easy to work backwards here to see which point a value is incorrect, since its all just simple math
ok il debug those but keep in mind i DO NOT know simple math, i did not pay attention in school
Good opportunity to learn it then
can you use a calculator?
no one was saying to do it by hand, but its simple math in that u can plug it into a calculator immediately
compared to something like rotations, quaternion math, where a vast majority in here would not be able to do it even with a calculator
what should i compare the minutes to? like the minutes to the hours?
like if elapsedMinutes are same as minutes in elapsedHours
you know if you switch to using TimeSpan you wouldn't need to be doing any of this
well id pray that your calculation of minutes / 60 is correct, i was saying to check if the minutes make sense logically. Like pause the game, look at the time in TimeManager, then check if you get the correct results in UpdateLabel.
hi i am having problems with my dash as when i dash upwards it sends me further then when i dash left or right can someone help me?
!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.
yoiu are going to have to really debug your code, you are mixing AddForce and setting velocity so it's impossible for us to know exactly what is going on there
Are you jumping and dashing? If so that could be an issue
I'm actually losing my mind. How is something as simple as "setactive" fucking me over
at a guess because when a gameobject is inactive none of it's scripts will run?
it's not the gameobject's script, so that's not the issue :(
setactive is only valid on a game object
yeah, but it's not on the gameobject that it wants to set active
You need to provide actual details for your issue
!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.
Also is you rlog running?
private void Update()
{
Debug.Log("Menu is " + menuIsUp);
// Check if Olimar is within the Onion's collider
if (Vector3.Distance(olimarTransform.position, destination.transform.position) < distance)
{
Debug.Log("Olimar is within distance");
if (Input.GetKeyDown(KeyCode.Space) && !menuIsUp)
{
menuIsUp = true;
onionMenu.SetActive(true);
logicManager.Pause();
Debug.Log("Paused");
inputCoroutine = StartCoroutine(CheckForInputCoroutine());
}
}
if (menuIsUp && Input.GetKeyDown(KeyCode.Space))
{
UpdatePikmin();
menuIsUp = false;
onionMenu.SetActive(false);
logicManager.Unpause();
StopCoroutine(inputCoroutine);
}
}
yeah the log comes up as if it's working properly
have you checked if your onionMenu is actually on using your script?
the script looks fine to me
yeah, I tried it in Start and it works fine there
as long as your debugs are going
Well, you have an if statement back to back. When you turn menuIsUp = true , it will immediately run the next if statement because it's now true and you're pressing space.
Unsure if this would be the correct channel, but I am using the Starter Asset Third Person controller, and for some reason sometimes if I bump into stuff or fall too hard the jump just stops working. My project is just to show off my level design skills but is a jumping puzzle, and I would probably lose points if my teacher has to restart, any way to fix this/ find out why its happening?
Well, maybe not, depends on what's happening in your pause.
Put a log in your second if statement and see if they both fire
oh my god thank you
I can probably just make that an elseif statement inside the distance checking if
thank you so much, christ
I would flip the if statements. Do the distance check inside the input one.
Either way, organize it however makes sense to you.
what is the trick to make properties visible in the editor again? 
oh [field: SerializeField]
Fields need to be serialized to show in the inspector. To be serialized they need to follow these rules:
https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
That single issue was actually driving me nuts for so long, I was put off from making progress on my game. It's like a massive weight was lifted off me lol
how can I generate trees (and other things like bushes or entities like enemies) in this type of procedurally generated terrain
you can use white noise to generate possible placement positions, and discard the ones that overlap with other structures or are out of map bounds
Okay, IΒ΄ll check it out then, thanks!
any suggested resources for learning how to make dialogue systems?
to clarify, for someone who is just starting out and trying to get a grasp on it
lmao
I just made one
It was from a tutorial from Brackeys video
his videos are really good
And even if your dialogue system isn't the same you can tailor it
to your project
but if u want the player to have dialogue choices too then you gotta rework the entire thing
I'm working on doing that now and it doesn't look like it
{
_rb.velocity = new Vector2(_horizontalInput * _moveSpeed , _rb.velocity.y) ;
}
else
{
_rb.velocity = new Vector3(0f, _rb.velocity.y);
}```
any way to stop micro movement from this code? what I mean by micro movement is a very small change in x and z, even though I have set velocity to zero in x and z
do you have a controller plugged in? could be giving the small input
nah, I'm using keyboard currently
what type is _horizontalInput?
float
you're comparing it to 0; try using `Approximately or check if it's less than a threshold value . . .
ah ok thx
can anyone explain to me why do I get an error when I do have a button called "Inventory"
What's the error say
The first step is always to read the error
Argument 1 cannot convert string to int
Right, now look at the GetMouseButton function:
https://docs.unity3d.com/ScriptReference/Input.GetMouseButton.html
public static bool GetMouseButton(int button);
what kind of parmeter is that expecting?
inb4 he has a UI Button called Inventory
Correct. "Inventory" is not a number
yep, just waiting for the reveal . . . πΏ
so I can I know the int value?
int value of what?
and blame him https://youtu.be/LaQp5u0_UYk?t=456
In this video weβll create a UI for our inventory that is highly flexible for different sizes and scales nicely for different inventory types. We'll set things up so you can call up your menus with a button press and pause the game while browsing your items.
This series is designed to be quite powerful, scalable for large games, and flexible en...
Did you read the docs?
The button values are: 0 for the left button, 1 for the right button, 2 for the middle button.
Which number of mouse button do you want to press
why would I blame him?
He's calling a totally different function
you should probably copy his code if you want to use the tutorial
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 177
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-08-27
is it bad if i changed version
you can use a newer version. that will migrate your project over to it . . .
does it break my script?
no
nah, only if there are breaking changes . . .
so its safe if i migrate rn?
it's a patch version change
Yeah. I would personally make a backup just in case though
Well i alreadt migrate it :/
you should be using Version Control regardless
so its still fine
what is that
its a system that tracks your project, any changes gets documented, each time you want to backup the project you "commit" the changes , you can revert to any state at any time
its really something that will prevent future headaches if something goes wrong with project especially
any tips on what to use that is not github? because i cant load my projects to github since they are to big π¦
did you use the proper gitignore, you generally don't need that much.
how big is the assets folder?
i dont know it is the right gitignore i just use the unity one. its well over 20gb π
and github says max 5gb
the assets folder?
I think with that size you will have trouble any VC without paying boats load of money
ive stoped making stuff in it i will double check just cant remember the name atm
if its the actual assets folder and mostly 3D assets that dont change, offset them to big storage like google drive n such while keeping VC for the rest of the project
sounds to complicated for me ;:(
oh it was 3.8 gb the assets folder.
you should be good then
it says its to big π¦ maybe im doing something wrong ....
what does?
the initial commit says to big with some random lfs comment that i cant remember from my brain atm
well first i would check if your github was actually added properly to the first commit, then would enable LFS if each individual file is bigger than typical size per-file limit
i dont know how to enable lfs π dont even know what that is .....
simple google π
https://docs.github.com/en/repositories/working-with-files/managing-large-files/about-git-large-file-storage
that link does not say anything aboutn how to enable lfs it only explains what it is π
did you click the breadcrumb uptop?
breadcrumb?
A breadcrumb or breadcrumb trail is a graphical control element used as a navigational aid in user interfaces and on web pages. It allows users to keep track and maintain awareness of their locations within programs, documents, or websites. The term alludes to the trail of bread crumbs left by Hansel and Gretel in the German fairy tale.
im way to stupid for this. thanks for the help though. that only led to the weird console thing where you need to enter shitloads of weird lines to get it to workΒ΄....
You mean git
that's how git works
***** Profanity words π
why make it so complicated...
:_D will never be that π im R3tarded π
i guess i will have to live without it π and hope my computer doesnt die π
if you plan on creating a game, using git aint the hardest part you will be doing.. its quite easy. enter a few commands and you're done
there are also GUI clients that exists (GithubDesktop, Fork etc.)
what? i have tried with tutorials and it never works for me..
Any recommendations of resources that teach how to fill a procedurally generated map with trees, enemies, bushes and so on?
break down the problem into smaller steps
you should use github desktop with git
wdym never works..it does work. Its not difficult at all
its extremely easy to set up
how do you plan on code if a few commands on console scare you
thats not the problem, problem is what the tutorial says should happend doesnt.
explain
like what?
cant remember exactly i kinda gave up on it 6months ago ish. but it was one of the lines that something should have happend it happend for my friend it worked for him. but when i did it it said the same thing but i still couldnt commit the big change
you can either use a GUI client to use git or use console commands
what? what big commit
so you got it working then if you can commit?
i think its better i try again and show you when the fault happends
maybe make a thread
hard to explain something that happend over 6months ago π now i cna hardly remembner how to use github or github desktop π
you should definitely get version control up and running
github desktop https://www.youtube.com/watch?v=5IxUElilf2M
The only thing is sometimes LFS gets weird on github desktop, might need to be enabled via terminal
i will try later today thanks π
i just followed a brackeys tutorial for my github desktop version control π
is the canvas gameobject disabled?
no
did you debug
the inventory menu is disabled
I mean its started as diasbled
i cant enbale it ingame
im talking about the gameobject this script is on
min 0:51 this does not happend for me i get this instead
press locate
remove
and find the folder
this is something old you previously had that was moved/deleted
wdym disabled
oki so remove for now
how can I disable a canvas
make a thread.
also
remove any git / gitignore folder(make sure show hidden files and folders is on) in the project so you start fresh
you mean the V sign below the inspector?
scripts wont work if the scripts gameobject is disabled
show the inspector where you put the script
does this get disabled?
make a thread.
no
did you debug if the code was even running?
put Debug.Log and see if it runs at all
Add this log outside the if:
Debug.Log($"{gameObject.name} update - Button? {Input.GetButton("Inventory")} - Menu? {menuActivated}");
See if the button value changes while you're holding whatever you assigned to "Inventory". You might want to enable collapse in your console
Does menuActivated change whenever you press your inventory button?
Can you show a screenshot of the console after you press the button once?
With collapse enabled, so all of the lines will show as one group
Enable collapse
Can you share the full !code of the script? The entire script?
π 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.
With the log included
I pasted it there how do I send it to you
send the link
Did you actually save the script like this? Because there's no such thing as menuActivateds so this shouldn't compile
I did it as the normal way then I changed it to that to see if it will do anything
wait
you mean
There is no "normal way" for menuActivateds to be written. There's nothing with that name in the script
waits its not the problem
As shown, this shouldn't compile
I thought u meant the ==
cuz some poepne dont like that
u can ignore the s
its a my misstype the code is as it should be
its not a compilation problem
Okay, did you make any other changes to the code as you were pasting it into the website
nope
Okay, remove that log and put this one inside the if statements:
Debug.Log($"{gameObject.name}- Menu Activated: {menuActivated}. Inventory Menu State: {InventoryMenu.activeInHierarchy}");
it doesnt show anything in the console
I think its might be a problem with the if statements
Can you show a screenshot of your full unity window with the console open, with this object selected, during playmode?
sure but the console is empty
do it anyway
ok
Okay, as a warning, you have errors disabled in your console. You don't seem to have any errors, but you'd be hiding them if you did
This is what I wanted to see, if anything came up while you were playing
ok
because any error could prevent your code from completing
Add this after your last else if statement:
else {
Debug.Log($"{gameObject.name} did not enter any condition. Button: {Input.GetButtonDown("Inventory")}, Menu {menuActivated}, Inventory Object: {InventoryMenu}");
}
And show this screen again after you attempt to press "Inventory"
yes it does that
it says it doesnt get the button input
should I screen shot the inventory button in the input manger?
It seems to be reading as Input.GetButton but not Input.GetButtonDown? I'm going to try to check something.
Hmm so it checks the wrong function?
I don't have Unity on this machine, can you send a screenshot of your "Jump" button in the input manager? It should be already set up by Unity
omfg I fixed it
it was so stupid
Something in the input manager settings?
Yep, that'd do it I think
anyway thank you for your time
rate my plane code
best to !code with these links . . .
π 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.
rb is a Rigidbody component you assigned from the inspector. why are you getting the Rigidbody component again to change useGravity?
rb is already the Rigidbody component. just use that . . .
true thats right for the gravity this is my simple plain control
using GetComponent in Update is bad and you can avoid that . . .
i have make that script is it good ore wath i can do better
i just mentioned it. you'd do rb.useGravity instead because rb is the Rigidbody component . . .
you have movement += transform.forward * speed * Time.deltaTime; but you create Vector3 movement = Vector3.zero; in the previous line. there is no need to add. you can condense these two lines into one . . .
Vector3 movement = transform.forward * speed * Time.deltaTime;```
yes you are right
when you rotate with transform.Rotate(+Wendigkeit * Time.deltaTime, 0 * Time.deltaTime, 0); you are multiplying deltaTime by 0. this is pointless, as it will always be 0 . . .
thgis is also better Vector3 movement = transform.forward * speed * Time.deltaTime;
hello! where can i ask a firebaseauth code question?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
!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.
Does somebody know why my GameObjects are instantiating between my tiles? (I mean, not in the center of the tile)
https://gdl.space/duxivumawo.cs this is the code with which I paint the tiles and Instantiate objects
Hi Pingu, from a quick look there's a good deal going on in your code. My first recommendation to you would be to break down your code into the tiniest possible bit, to help isolate what's causing your issue. Probably the easiest would be to comment out stuff and/or make a separate script that spawns GameObjects onto tiles, but create your own tiles, to simplify that part of your code. That will help isolate if it's in how you're instantiating GameObjects, or if it has something to do with the perlin noise.
Again, this is just from a quick look, but I'd try it and see what it might show you!
Oh, my bad, this isnt the full code, these are two exctracts from two different scripts, one generates the terrain (PaintTiles) and the other one Instantiates the Objects
No worries! All the more reason why I would break this down into smaller, tinier bits to help process what's happening.
Another simplification step could be spawning just one unit, and see if you can get it to spawn in the center of a tile. Start with drilling down into the core of this code. Was this from a tutorial?
if they're spawning between tiles and not centered on tiles.. then it must be the way u calculate the x and y coords
It is the same on both scripts since I pass the same Roompositions
i have a question about negative numbers related to coding. I'm currently using a value to determine the player's velocity as a single number, the problem is that the value only detects the player's velocity in their forward direction. I would like to detect their velocity omnidirectionally to have an accurate velocity value for when they collide with objects. How could I go about doing that?
{
generalVelocity = Vector3.Dot(body.transform.forward, body.velocity);
}
Not really
Oh it surely is this
you are totally right, let me check
use velocity.magnitude
oh my lord i forgot that was a thing
but doesn't that only return a value between 0 and 1?
they still are instantiated wrongly
it returns the length of a vector..
it ignores the direction
oh wait 0-1 is .normalised
big up
1 is normalized. 0 would mean you have zero vector
sorry, im not good at tiles.. i just figured id throw out my best guess
DonΒ΄t worry and thank you anyway!
good luck π
isnt it b/c u specify the transform.forward?
wouldnt generalVelocity just be rb.velocity?
ya, 3 floats.. a singular vector3
(that would be all ur velocities)
whats the code for?
detecting the overall speed of collisions in a direction
the problem was that getting .velocity itself gave me negative numbers for when the player would collide with something in reverse
what's that?
is this a property?
thats a Mathf function
oh its mathf.abs
im gonna be completely honest i had no clue how this function worked up until now
lol.. it gets the distance from the number to 0
soo negative numbers end up positive
positive numbers stay posiitive
oh man thats really useful actually
but yeah its pretty important because I want players to be able to collide with other objects in the scene at high speeds and deal damage based on their own velocity
is there a way to lock float values in the editor to a decimal point like with the .ToString("F1") method?
How do i make an array accept negative values like it would in python? (nvm, i figured it out)
you'd need to write an editor script / w an OnValidate method to round it everytime u made a change
What do you mean, arrays arent limited to storing positive numbers. If you're trying to access it via negative index, you use ^
arrays can always use negative numbers
now.. if u mean negative array index's no.. lol
yes, this, but I figured it out
ahh okay
Yes you can, as I wrote above. arr[^1]
i was reading this.. edit: dang that post is 9 yrs old
absolute value.. is that wat the ^ is
Means "from end"
You can do substrings and collection slices with them, in modern .NET
One of these is an index, a pair of them a range
string s = "hello";
s[1..3] // "el" (1 to 3)
s[..^2] // "hel" (0 to 2-from-end)
TIL
They're cool, and of course you can use variables in these, you're not limited to number literals or constants
i think i understand now
Ah yep you have the analyzer telling you that you can simplify the regular substring into the "slice" substring
They both compile to the same code, so they're equally performant
not a huge fan of the new string stuff, starts to look a bit convoluted. perl is a perfect example of it going too cryptic
lol, just noticed that
im all about learning some new syntax
may never use it.. but its cool to know
After using rust, I much prefer the new range syntax personally 
There's always worse, you haven't yet stumbled on the latest pattern matching (with is) implementations
You know you're in the deep end when you start seeing stuff like [ 2, _, 3, .. ] and [..var r]
while we are on interesting string stuff, I was curious if you could change a string in-place, and you technically can. It could break, but that's okay 
var test = "Number 1!";
unsafe {
fixed (char* ptr = test) {
ptr[test.Length - 2] = '2';
}
}
// Number 2!
Debug.Log(test);
yo, what do i do?
My guess: You have variables with the same name as the old obsolete MonoBehavior methods, like having a public Collider collider or public Rigidbody rigidbody. You should click no, then probably go rename those so Unity stops complaining
this is the code, i added, are there any variable names like that?
public RaycastHit hit;
Vector3 bottom_pos = player3.transform.position + Vector3.down * player3.collider.height / 2;
if (Physics.Raycast(bottom_pos, Vector3.down, out hit, 0.1f))
{
if (hit.collider.CompareTag("Ground"))
{
is_jumping = false;
}
}
it might be the first line but i'm not sure
player3.collider is the one triggering it
what should i change
Whatever player3 is, go to its script and rename the collider field to something else
Pay attention to the warnings (underlined green-ish / yellow) that say that your variable is "hiding an inherited member"
but i'm trying to get the height of the collider of player3
So it's not one of your own variables?
yes
What's the type of that player3? GameObject?
yes
Okay so yep Unity complaining is purely normal here. Nowadays you need to use GetComponent<T>() to get a component attached to a GameObject
So get the collider using that, and you'll be able to get its height just fine
Or even better, change the type of player3 from GameObject to Collider so you can access it directly. You'll still be able to use .transform on it!
hey so i have this weird bug in my game where my enemies which normally should just go towards the player the entire time but if i punch them a couple times they just go in the direction i punched them
public class EnemyMovement : MonoBehaviour
{
Transform player;
public float moveSpeed;
void Start()
{
player = FindAnyObjectByType<PlayerMovement>().transform; // Find the player object
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime); // Constantly move the enemy towards the player
}
}
thats my enemy movement script anyone know why this is happening
is there some rigidbody or collider setting i need to change
Does the player move?
yeah
If player is already a gameobject.transform
Why use player.transform.position
And not just player.position
not sure the tutorial i watched did that i kinda assumed it did smth different
Can you try by removing the first .position? The one when setting the value of player
nope didnt fix it
PlayerMovement is a script? (Ig yes) Is it only attached to one game object?
yep
public class EnemyMovement : MonoBehaviour
{
GameObject player;
public float moveSpeed;
void Start()
{
player = FindAnyObjectByType<PlayerMovement>(); // Find the player object
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime); // Constantly move the enemy towards the player
}
}
Try this maybe? And make sure moveSpeed is never negative (which would make your enemy go away from the player)
trying to apply it to my script and it is absolutely beating my ass
im sort of at the halfway point, where he's linked up the continue button to cycling through dialogue, but ive been trying to get it so it shuts down the movement and camera script i have on my player, and its showing that both of them are getting shut down, but then my player can still move
the idea is that when they enter the prompt to interact with the player, it'll stop them from turning away or walking away while still being in the dialogue. when it hits the last dialogue, it'll just release them again
i got it to work for my other menus but suddenly this one wants to be stubborn
naps are necessary
still doesnt work it seems to be randomly when i like spam punch them they glitch out and start just slowly going in the direction they where hit but it looks like they are trying to go to me at the same time so they like jump back and forth its really weird
Do they have other scripts attached?
the enemys have a sprite renderer a capsule collider 2d a rigidbody 2d a health script and the enemy movement script
oh and then it'll say "hey this thing doesnt have a reference"
wdym it doesnt have a reference
you are very clearly deactivating the reference
So what makes them go away when you punch them?
well its like moving into them my characters fist has a collider that knocks them back
yeah movespeed doesnt change
So idk, sorry
all good
Are you using physics? Check the velocity of said enemies, if you are.
so that does seem to be the problem i think but im not sure how to correct it
as i noticed that a enemy that was moving away from me had a x velocity of 5
Maybe instead of setting the position (via move towards Transform), set the direction of velocitycs [SerializeField] private Rigidbody rb; private void FixedUpdate() { rb.velocity = (player.transform.position - transform.position).normalized * (moveSpeed * Time.deltaTime); }
If you've got some knock back feature, you'd probably want to disable movement for some duration while still being knocked back
pls help
I'm trying to find the problem for 1 day and i couldn't
if someone can see where's the mistake pls tell me
this is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class SkeletonBattleState : Enemystate
{
private Transform player;
private Enemyskeleton enemy;
protected int moveDir;
public SkeletonBattleState_(Enemy enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_skeleton enemy) : base(_enemyBase, _stateMachine, _animBoolName)
{
this.enemy = enemy;
}
public override void Enter()
{
base.Enter();
player = GameObject.Find("Player").transform;
}
public override void Update()
{
base.Update();
if (player.position.x > enemy.transform.position.x)
{
moveDir = 1;
}
else if(player.position.x < enemy.transform.position.x)
{
moveDir = -1;
}
enemy.SetVelocity(enemy.moveSpeed * moveDir, rb.velocity.y);
}
public override void Exit()
{
base.Exit();
}
}
player = GameObject.Find("Player").transform;
this part basically can't find the player, but in the scene there are the player named exacly how it's written
I see some videos and search to understand how the gameobject.find works but it seems alright for me(I know it isn't but i can't tell what's wrong π¦ )
have you verified the code even runs?
with a Debug.Log
Error says you've got an nre (null reference exception) on line 28 of skeleton battle states
yes
you couldnt have since you have an error
Looks like a runtime error (196 of them)
when i tested to see if the player is returning the gameobject or as null it says null
its in update
did you not assign a value in the inspector?
What line is 28?
if (player.position.x > enemy.transform.position.x)
no
One of them is null
i'm doing this code following a course
its player
but i can't do the player(transform) recognize the player(gameobject)
You'll need to assign player a reference before using the variable
non english speaker my bad if i say something wrong or confusing
if i'm not mistaken its this right?
private Transform player;
That's just declaring the variable
πΏ
have you assigned said variable?
You'll either need to assign it through the inspector (via with a serialized field attribute for private members or as a public member) or Find - preferably the first.
ok
so thats not assigned then?
apparently not
then assign it and you should be okay
What you're doing is basically saying: there's gonna be a table in this room and never actually putting the table there. So when you want to use the table, the space-time continuum breaks.
omg
interesting table analogy
ok
I make it public and assign the gameobject player
but the error still happening
π₯Έ
same error or different error?
Did you reference the player in the scene?
also you do not need to make it public to assign something via inspector
the knockback is just from the fist collider pushing it back
i will try this in a little
same
yes
Did you save the script?
yes
Can you show us the updated error?
hmmmmmm
public SkeletonBattleState_(Enemy enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_skeleton enemy) : base(_enemyBase, _stateMachine, _animBoolName)
{
this.enemy = enemy;
}
is this.enemy = enemy; supposed to be in a start method?
try putting it in a start method
start method?
as far as I know yes
ok
its not in any
the void Start()
thats probably why
I am not crazy, i assign the player gameobject in the public variable returned to the code and it disapeared
im not crazy
i swear
you dont assign it while in game
I'm assuming everything works now
it will revert when you do
yes i dont
Had probably forgotten to save
CTRL + S game not on point
just give a warning but nothing happen
the player arent assigned
This doesn't do anything btw
yes i know its not capitilized
is there a way to make OnCollisionEnter work for gameobjects that don't have the script attached to them?
His original method takes an enemy parameter and assigns it to his enemy (explicit this). The start method doesn't receive an enemy thus just assigns it to itself (no work done)
then there is something wrong with his SkeletonBattleState_ script
I'm assuming it's called elsewhere (likely a constructor method) and a part of his tutorial.
Which makes little sense as the Unity messages imply that it's a mono behavior (which has no constructor)
he should go back in his tutorial where he wrote this script and should check then if enemy is actually found
guys i think i resolve it
i forget to tell that im using hierarchy
so i put it in the main code
and it appear
sorry
π
but now other error that wasnt there appeared
with the enemy variable
π©
enemy.SetVelocity(enemy.moveSpeed * moveDir, rb.velocity.y);
this part
the same error

remove the start method (if you still have it) and go back to your original
i removed already
same error
π
a new error or the exact same error as last time?
same
Figure out what's null and make it not null
How do I make a bullet ignore collision with the object that created it? I know i have to use "Physics.IgnoreCollision(the collider from the thing that instantiates the bullet, GetComponent<Collider>());" How do i access the collider from the thing that instantiates the bullet
You tell the bullet who that thing is
how
its an enemy so theres many of them
and i need it to hit other enemies, just not itself
For instance...cs var bullet = Instantiate(bulletPrefab); bullet.owner = this;
oh its bullet.owner?
Well, you'd use your own names and whatnot but the important concept would be caching the instance and informing the instance who the shooter is.
I FIXED IT
Or have the shooter setup the ignore collision
THANKS @ivory bobcat @steep rose
π€
what did you do to fix it?
i will have to see the video again
var bullet = Instantiate(...);
Physics.IgnoreCollision(collider, bullet, true);```
what i did was to declare from where the rb.velocity.y was comming from
basically
i have to return the way it was before this conversation even starts
thats why i will see the video again
but i dont think this causes any trouble the way it are now
just make the code a bit messy if the people seeing are a complete perfectionist
but thanks for the help
does doing "var bullet = Instantiate(...); actually instantiate the object? (ive never used var before)
Instantiate returns the instance that is created.
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
i see, thank you
for the enemies own collider i just do GetComponent<Collider>() no?
That or have a private serialized field and assign it through the inspector.
ill try the second one, its telling me it cant find the enemies collider (which is kinda weird imo)
cos it does have a collider
Implies that you've got a field called collider and that the bullet prefab is a collider referencecs [SerializeField] private Collider collider;//Assigned from the inspector [SerializeField] private Collider bullet Prefab;//Assigned from the inspectorwhere the instantiated instance would be a reference to the object as it's Collider component.
wait its a box collider 2d, does that interfere with something?
Use physics 2d for 2d stuff
https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html
You'd also use the 2d variants for the fields and whatnot.
whenever I'm trying to see if something is within a certain distance of something else I just use a raycast with a certain length
is there a better way of doing it
Vector3 targetPos = obj2.transform.position - obj1.transform.position;
if (Physics.RayCast(obj1.transform.position, targetPos, out hit, 10))
{
debug.log("in range")
}
just an example
you can use a Physics.Overlap of some sort
idk what that is never used it
look at the docs, its pretty easy to use
I see
what about seeing if a something is in eyeline
like i have flashbangs that check if there's a direct path to the player
and turrets that aim and shoot if they're in eyeline
is a raycast not just a better version of that
with a raycast you'd have to give it a direction & distance
linecast automatically computes the direction & distance
but yes, you could achieve the same result with a raycast
I mean that's literally just ,15 at the end of it
This might be a silly question but having some difficulty identifying generics (fairly new to integrating generics into non generic scenarios)
I have a ScriptableSetting class which inherits from ScriptableObject and then a ScriptableSetting<T> class that inherits from ScriptableSetting. I'm doing some editor window stuff where i wanna show a list of all the stuff inside them and im fine doing that in a generic function but i don't know how to find and cast every ScriptableSetting<T> to start off this whole thing if that makes sense
Like usually i'd type check and cast but i afaik i can't type check to see if it's the generic version
i think im just doing this allwrong
im guessing i need some little box that helps me ungeneric-ify the info kinda how serializedproperties and unityevents do
chat is dead
If you just want to check distance, you can use what you already have. This will give you the distance ```cs
float distance = (obj2.transform.position - obj1.transform.position).magnitude;
if (distance < 10) { }
It's the same as using the ```cs
Vector3.Distance(obj1.transform.position, obj2.transform.position);``` method, and you compare the returned value against 10. This doesn't involve raycasting, the physics engine, or needing to have colliders . . .
how does a vector3 to float work
vector3 = 3 floats
A Vector3 consists of 3 float values. That is the type of the position property of a Transform . . .
No one said floatvector3. That is not a type . . .
Vector3.Distance is a Unity method that returns a float . . .
it would look exactly like a compile error
It's the same as doing . . . (obj2.transform.position - obj1.transform.position).magnitude;
original author of hte method is a guy named Pythagarus
good one
Don't say his name three times . . .
Is SpriteRender.bounds extremely inaccurate or am I doing something wrong?
var newPos = new Vector2(Nozzle.position.x + movement * speed.x, Nozzle.position.y);
print(GantryRenderer.bounds.size.x/2);
if (newPos.x < Nozzle.position.x && newPos.x < GantryRenderer.bounds.min.x) return;
if (newPos.x > Nozzle.position.x && newPos.x > GantryRenderer.bounds.max.x) return;
Nozzle.position = newPos;
The Highlighted Object should not exceed the others boundaries
Is there any way to get the "local" position of a GameObject? I took a look at transform.localPosition but that looks like it's relative to the main parent which still uses world position.
each time I move a different transform to the gameObject + -1 on the z axis it moves to a different side, I really need it to always move it to the same position relative to the gameObject
this seems to work i am gonna test some more but i dont seem to be having the same issue
only thing is speed has to be changed a lot but thats a simple fix
also i asked a ai to try and figure out what movespeed should be so it is the same speed as before and its saying that its a lot slower because im multipling by time.deltatime twice is this true?
or is my ai bugging
localposition should give you the local position of current parent of that object
if you want a local position relative to a greater parent, I usually do something like taking the world position and sticking it into this method:
https://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html
I made the enemy patrol but the patrol process is very fast how do i slow it down?
I want local position relative to the gameobject, not a parent or child
Should've specificed π
check that method then
alternatively, cache the starting position of each and accumlate units
I just got an insane amount of errors after following through a course and I'm not sure on how to fix all of these errors. If anyone could help it would be appreciated.
you'd probably want to give us an idea what the code looks like
how do i share?
well, your first error there is a null reference error, so something isn't set in the inspector or isn't instantiated in code so figure out where that's happening
!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.
honestly the translate seems fine to me, and the speed isn't anything bizarre?
This seems interesting.. Might be what I need
it looks fine but it is not giving right result
yes , that is the thing i want to fix
I mean your value of speed there. Is it set to 1 for the sake of testing here?
So, I've not done a 2D platformer for a while, but I wouldn't actually rotate but instead inverse the scaling
for when I would do the flip() stuff
So, I'm not too sure if the behaviour of rotating on the y here by 180 is correct
Vector3 creatureRelative = closestCreature.transform.InverseTransformPoint(closestCreature.transform.position);
gameObject.transform.position = creatureRelative + teleportOffset;```
ignoring that this isn't formatted correctly, would this be the right setup for InverseTransformPoint? From what I've read on the documentation you provided it seems good
teleportOffset is just Vector3(0, 0, -1);
the dot operation is called on the object you want to use as the relative object which you feed a world position to and get back a return that's now in local space relative to that transform
there's also a matrix4x4 method that does similar if I recall
I'm assuming I have everything around the wrong way then because I'm just teleported to 0 0 0
Well, 0, 0, -1
in your code you're using the method on the same transform so yes you're going to get a vector 0 position
a better idea of what this method returns is say you want the local value if you were to child an object to another
Oh I think I get what you mean now, should I be using the gameobject I'm teleporting's transform instead?
If not I do not get what you mean now
If it's local position relative to the position I enter then it makes sense to use the gameobject I'm teleporting, sorry if you've already said that.
im not entirely sure of the use case here, but I'd experiment between those objects
I usually use this method for when I want local coordinates without having to child that object
because childing objects also force rotational local values onto that child
while sometimes I just prefer having those local positions ;p
the cutting recipe so array has all the kitchenobjectso in the inspector so im not sure where the problem might be
oh, so does it flicker at 0 too, thus not translating at all? I can only guess maybe the rotation is being applied to a pivot that's centered to this level.
i think so
but I looked it up and 180 rotation on the y is fine, and so does flipping the scaling on the x
well, your code shows two possibilities it can be on line 119, I suggest using debug.log and checking each one of those variables for if one print null
@cosmic dagger Thanks for the help yesterday, Got the thing I was working on mostly-ish working. Architecture wise it's abit overengineered but happy I mostly figured out what I was trying to do
the serialization in the window is rough because its accessing those values in a way where actual game mechanics and/or a fully fledged options menu could access them at runtime so abit harder to use unity's built in stuff to handle it
i see that there are no cuttingrecipeso here
i checked in the inspector again
Oh, yeah the data type looks wrong. Show the SO script
you should be extending from ScriptableObject if you arent
havent seen createassetmenu invoked like that but otherwise looks fine
maybe try CreateAssetMenu(menuName = "CuttingRecipes")
then create it from the asset menu
where should i paste this code down?
look at your screenshot and toss what's there inside of the parentheses
oh alright
oh there was a problem here also
alright i fixed the vegetables error
now im having errors on cooking the meat
Thats what this method doesβ¦. It just logs an error
oh wait hold on
Did you mean to just test it with debug.log ?
i was using debug.log for the other error i had
now i was checking if the game ran fine but it showed an error on the stove counter
hi can someone tell how i can make and object 1.5f away on the z axis from a target object and basically do this?
easy solution: child it
Or math
i don wanna child it i want them to be separate
how?
Could probably use a parent constraint component if you want the parent effect without parenting
oh also i want the object to rotate around the target which is working
this is what i am doing
Assuming you're going to be rotating the target as well
https://docs.unity3d.com/Manual/class-ParentConstraint.html
can i add this parent constraint through code to an object bc i am trying to rotate the foot as you can see in the photo it works but it is crooked when the character is rotated any degree other than 0
Maybe just have it inactive and activate it whenever you're needing it.
tbh i cant so i will have to find away to do this
Im getting an CS0229 error because there's some kind of conflict with two members named input in my project. Can anyone help me figure out why this is happening?
- !code π
- you have two of the same type, likely an accidentally duplicated script file
π 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.
alr thanks for the help
private void HandleMovement()
{
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 move = transform.right * moveX + transform.forward * moveZ;
Vector3 velocity = move.normalized * movementSpeed;
velocity.y = playerRigidbody.velocity.y;
playerRigidbody.velocity = velocity;
}
Why does my player still keep moving for a split second after I release the move keys? I used the same script from my last project and that one did not have this issue.
use GetAxisRaw if you want it to stop instantly
Okay, any idea why my other project kind of smoothed it out when stopping? This one just kinda snap stops it
Its all the same code
Likely friction
I also used same material to remove friction
I'm assuming the scenes are different
Yea they are not all the objects had no friction
Are the scripts the same?
If the scripts are the same then it's likely something from the environment causing the character to either decelerate or accelerate faster
In one project I have more fps even tho it has more stuff then the other one so idk tbh
Thanks anyway
Have a blank scene in both with the bare minimum and see if the two projects run the same. Then slowly incorporate stuff till they differ.
Hi, Im new here. I started learning Unity last week to help my friends son with their schoolwork.
I'm having a problem when I push my Unity project to Github using the Github .gitignore. When I clone the project back down to a new folder and open it in Unity, heirarchy is reset like a new project. All the gameobjects are there in the project pane and it builds and runs fine.
Any idea whats going on?
sorry, where should I post this? new
well typically you would post it in #π»βunity-talk but i've already answered your question so you don't need to repost it there
Hey all,
I have an issue and I couldn't find a solution yet.
That rod animation and the line physics are not synced. Line logic is in FixedUpdate and Rendering that line is in LateUpdate.
Also first particle of the line is always same as tip of the rod position and it is in FixedUpdate.
I've tested to put it in the Update or moving rendering to Update or FixedUpdate but still same issue.
Any idea on that ?
fixed update is 50 times per second, update/lateupdate is however many fps you have. these 2 will basically never be in sync.
moving the rod in fixedupdate should be fine but that does depend how you're actually moving it
By animation. I've changed the animation Update Mode to Animate Physics for testing but it was the same
Hi again. I'm trying to create a place to store global game state. I'm thinking of storing this in a script called GameState.cs and following the advice from here with public static variables https://discussions.unity.com/t/c-how-to-access-a-script-not-attached-to-a-gameobject/648267/2
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using Unity.VisualScripting.FullSerializer;
using UnityEngine;
public class GameState : MonoBehaviour
{
// Start is called before the first frame update
public static Dictionary<string, object> globalState = new Dictionary<string, object>();
public static int numberOfPlayers = 2;
private void Start()
{
globalState.Add("status", "menu");
globalState.Add("playerCount", 1);
}
}
Then accessing the script from another script in the same scene like this;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.SceneManagement;
public class StartMenuLogic : MonoBehaviour
{
[SerializeField] UIDocument mainMenuDocument;
private Button settingsButton;
private void Awake()
{
// define the form elements
VisualElement root = mainMenuDocument.rootVisualElement;
settingsButton = root.Q<Button>("settingsButton");
settingsButton.clickable.clicked += openSettings;
}
private void openSettings()
{
print(GameState.name);
}
}
But I get "an object reference is required for the non-static field" on GameState.name.
Does this mean GameState is non-static or GameState.name is non-static or something else?
the class GameState is non static and the variable name is also non static
If feels to me like GameState is not being imported. Am I missing something? That article is from 2016
Assets\Scripts\StartMenuLogic.cs(56,15): error CS0120: An object reference is required for the non-static field, method, or property 'Object.name'
Is there an updated guide on accessing scripts from another script?
Either you need to make GameState static (and drop the monobehaviour) or use the singleton pattern
Like
public static class GameState
yes, then you need to change the Start method as well because that wont execute automatically
Hey, I cant understand timeline workflow. When I hit play nothing logs at all, but when I pause playmode and go frame by frame manually then I have logs, but instead of 5 times, its 8?
I have no idea what is going on here
So;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using Unity.VisualScripting.FullSerializer;
using UnityEngine;
public static class GameState
{
// Start is called before the first frame update
public static Dictionary<string, object> globalState = new Dictionary<string, object>();
public static int numberOfPlayers = 2;
private static void Start()
{
globalState.Add("status", "menu");
globalState.Add("playerCount", 1);
}
}
how are you going to execute Start ?
No idea
I'm not sure what the issue is in general. If this is supposed to be a Monobehaviour then you did it wrong
It's not supposed to be all static, and it should inherit from the MonoBehaviour class
This is code-beginner right. I'm a beginner
Sorry, but these things should not even happen if you have everything set up correctly
He wants a script NOT attached to a Game Object
Ah, I see now. There was a conversation above
Bump
@languid spire Thanks for your help, all working now and I understand a little better π
This is fine if you want to very easily access static variables, but use a constructor instead to store the initial states
Even better would be to use singletons and to keep this script on a Monobehaviour.
you may want to read
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Generally having everything static like this is not a good idea in terms of scalability
Thanks all, I'll read that. This first project is not supposed to be scalable but I will read and learn for future projects
All good, but I suggest you still read about Singletons. While they don't apply here as much they will be required once you encounter single instance Monobehaviours that must be accessed from anywhere. This will be sooner than you might think. https://unity.huh.how/references/singletons
This is because MonoBehaviours can't be static like this.
Thanks, I will
for some reason i cant use Input.mousePosition when trying to assign it to a variable
im not sure whether its a problem with visual studio or a problem with my packages
show the !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.
im just trying to do what it says on the documentation
but everytime it just says it doesnt exist
So you decided to totally ignore the bot message?
Vector3 mousePos = Input.mousePosition;
do you have your own class called Input?
and do you have the input manager set to old or both?
post the complete script to a paste site
theres literally 5 lines of code
using System.Collections.Generic;
using UnityEngine;
public class Input : MonoBehaviour
{
// Start is called before the first frame update
private Vector2 mousePos = Vector2.zero;
public float maxPower = 10f;
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 mousePos = Input.mousePosition;
}
}
ignore the vector3 vector2 thing
i just fixed that
Ok, so when I asked if you have your own class called Input your answer was what?
no
and what is that class called ?
so what do you think the class name is then ?
ik its called input
so you DO have a class called Input then don't you
let me try something quickly
it was because the name of the class was input
great
i just needed to change that name
you will also need to change the file name
how do i change the size of a boxcollider2d in runtime? i see examples on the unity manual over changing the size of a standard boxcollider but nothing about a boxcollider2d
colllider2d.size does nothing
because you need to reference an INSTANCE not the class itself
And why are you using Collider2D when you know it's a BoxCollider2D ?
ok yeah changing the type to boxcollider fixed my issues
you have modified an instance of a prefab, you can update the prefab with the changes
but that will change all instances
if you have modified the prefab, you can remove the overrides on the instance
Prefabs are a special type of component that allows fully configured GameObjects to be saved in the Project for reuse. These assets can then be shared between scenes, or even other projects without having to be configured again. In this tutorial, you will learn about Prefabs and how to create and use them.
hello how can i switch from 2d to 3d
You make a new 3d project
no i switch to 2d
Then you make a 2d project
Bro can you make it understand its hopeless
Guys how to switch 3D because my camera become 2d idk how to change back
Just right click and move your camera
I dont have that
Do not post photos, use screenshots
idk this
@bleak hare You've been told already, this is not the code issue, stop cross-posting here
Your question is in #π»βunity-talk
can i store a video as a reference?
Hey I was wondering what if I used math.sin for the x and y pos? I remembered sin and cos both return a number of -1 to 1 right?

: 0
Can i solicit in your dm?
No
ok
Hey ! Right now, Iβm trying to create a 2D rogue-like game, but Iβm having a lot of difficulties with the attack system for the mobs. I'm not quite sure how to make it work properly... To summarize my attack system so far : The mob chases the player, and when it gets close enough, it stops and attacks using a BoxCollider2D that serves as a hitbox (thanks to the OnTriggerEnter2D() function). However, this isnβt viable because if the player doesnβt move, the BoxCollider2D doesn't trigger anymore, and thus the player doesnβt take damage... I'm not sure if I'm on the right track, so if anyone can help me, that would be great ! (PS : I can show my script if u want)
we would 100% need you to show your !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 doesnt matter if you're moving or not a trigger will still trigger, so you must be doing something to counteract that
Ok so this is my Hitbox script for my Mob
using UnityEngine;
public class HitboxDetector : MonoBehaviour
{
[SerializeField] PlayerStatistics playerStats;
private MobBehavior mobBehavior;
private CoroutineManager coroutineManager;
private BaseAttack baseAttack;
private void Start()
{
mobBehavior = GetComponentInParent<MobBehavior>();
coroutineManager = FindObjectOfType<CoroutineManager>();
baseAttack = new BaseAttack(playerStats, mobBehavior, coroutineManager);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
baseAttack.PerformAttack();
}
}
}
and this is the script for basic attack
using System.Collections;
using UnityEngine;
public class BaseAttack
{
// readonly = final (en java)
public bool CanAttack { get; private set; }
private readonly PlayerStatistics playerStats;
private readonly MobBehavior mobBehavior;
private readonly CoroutineManager coroutineManager;
public BaseAttack(PlayerStatistics playerStats, MobBehavior mobBehavior, CoroutineManager coroutineManager)
{
this.playerStats = playerStats;
this.mobBehavior = mobBehavior;
this.coroutineManager = coroutineManager;
CanAttack = true;
}
public void PerformAttack()
{
if (CanAttack)
{
coroutineManager.RunCoroutine(AttackCooldown(1f));
MobStats mobStats = mobBehavior.GetMobStats();
playerStats.TakeDamage(mobStats.GetDamage());
Debug.Log("Il reste " + playerStats.GetCurrentHealth + " HP au Joueur !");
}
}
private IEnumerator AttackCooldown(float cooldownTime)
{
CanAttack = false;
yield return new WaitForSeconds(cooldownTime);
CanAttack = true;
}
}
If you want the Mob to perform multiple attacks you should use OnTriggerStay
curious on why it doesnt execute when standing still
because Enter is only performed once
each time when something goes into the trigger
I know that but i think it's not "pro", i really want to do great
each time the player goes into the trigger
well yes, im going off the fact he tested standing still while not already in the trigger
if you want to do pro, redsign your system
how
hit box should be on the player not the mob
I already have an hitbox on my Player for attack mobs, so i must to add an new BoxCollider2D to simulate the mob attack ? (sry for my english :( )
you dont need 2, one hit box can do both jobs
so what i have to do with the mob ? Mob must trigger the hitbox on the player ?
Bump. Help please :>
guys i need help i dont hv any errors on unity but i am throwing bananas via object pooling i hv 10 bananas in unity but i encounter 2 problems, 1 the banana is not moving any distance and 2 the clones of the banans are not deleting themselves like my code says to
any fixes thanks
Hey guys! Im trying to make a 2d shooting game but the bullet falls down when I shoot. My shooting code:
public GameObject shootPos;
public GameObject bullet;
private GameObject shoot;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
shoot = Instantiate(bullet, shootPos.transform.position, Quaternion.Euler(0,0,-90));
}
}
}```
The bullet is a prefab
The components of the bullet:
There's nothing there that would make it move forward
do you set your speed?
oh i forgot to set it that must be it
you probably need to set the gameobject active status to false when OnTriggerEnter2D
ah what a dumb mistake thank you bro
so then when attack called, it will find the banana that is deactivated correctly
alr thanks man
you have to apply velocity after instantiate
Try Quaternion.Identity and remove rigidbody on ur bullet prefab
its still not working i set the speed and its only moving like 1cm and when i added that disable object it like only stays there for a second and goes away like a flicker so im not sure whats happening
@analog wren
what the speed value you've set?
i set it to 10
make the value larger? So then it can move futher before it get destroy by disable by the broke > 5
alr
seems like your direction is only for the size of the banana
its not working its still the same and its still doing the flicker thing
size?
Ok well it moved a bit but its still making a bunch of copies and not deleting its ef
self
i upped the cooldown
but its still making the copies and not moving any distance at all
ya so the speed is not making any difference
oh ya, try remove your rigidbody
rigidbody of what
this is what it looks like rn
its just making a bunch of copies with the click and not dleeting itself and not moving any distance
Can anyone help me fixx this issue thanks the code is here
im using object pooling but its not deleting itself and bananas dont move distance
Looks like it's colliding with something and stopping all of its movement and timers
Try putting a log in the on trigger enter
if this banana touches any object, it freezes in place and sticks around forever
iv never done a log statment before so how do i write it this is my first time
Debug log should literally have been the first line of code you ever wrote in unity
if you don't know how to do a debug log, you've gotten way ahead of yourself trying to implement object pooling
lol
the code seems fine like on my side, can you post a video on how it looks like on your side?
I can create the banana and it get destroy after it broke
it's no laughing matter. How did you ever expect to debug code?
bro i just found it funny cuz it was so basic its not a big deal
alright
the fisrt lines are just imports
is there any error?
nope
This has already been answered
the banana is colliding with something as soon as it spawns
Use logs to find out what
alright
i hv just added the debug statment so lets see what it i
it says its hitting my monkey @polar acorn
should i move away the firepoint far away from it
And do you want the banana to freeze in place forever when it touches the monkey?
nope
Do you want the banana to freeze in place forever when it hits anything
So, you should probably add in some code that makes it disappear
but i did
Where?
private void OnTriggerEnter2D(Collider2D collision)
{
hit = true;
circleCollider.enabled = false;
but when i set the gameobject to false
How does that make it disappear
then it just flickers and its not moving any distancfe
That, in fact, makes the object freeze in place forever and never interact with anything ever again
so if its hitting the monkey therefore freezing do i move the firstpoint farther away
firepoint
First off, you should make the banana actually do what you want it to do on collision with the things you actually want it to collide with
