#💻┃code-beginner
1 messages · Page 667 of 1
k i see
though gotta be a bit more precise - the actual classes inside each other, or class instances?
Okay, but having your "OOP script filled with classes and all good" doesn't tell us anything. It's best to give an example . . .
thanks to @naive pawn!
i solve all problems in my project
the way its gonna lets say, here in the script attached to the player inside of the public class provided, in the update method, i can put the classes i need in there
the actual class definitions or class instances
it seems like you don't understand these OOP terms?
Yes, you can just do that. It has nothing to do with OOP inheritance
not yet, i am searching up what you just messaged so i can have a proper reply 😭
I would just start coding to have something physical that we can look at and reference . . .
you should just go learn basic OOP so you have a good idea of what you can and can't do, and so you can also express your questions clearly
i messed up in that reply, after i call the line of script you mentioned earlier inside of my name space, i can put a random class, inside of that class, iw ill add a start method and put inside of it the class
It's confusing because everything mentioned is hypothetical (and complicated for anyone to grasp) . . .
i guess i am gonna go start programing the script so i can get a grasp and ask my questions properly. thanks @cosmic dagger @naive pawn @keen dew
I suggest that you start with very basic stuff first, it doesn't sound like you need any of the things you've researched so far. Don't make it more complicated than it has to be
i will start with movement and money/currency setup, but maybe in a hour since i am busy at the moment
so basically, on the one that on the build is the same as on the editor i got 60 fps capped 12 ms and the other one that on the editor is 10 times slower i got 800 fps 1 ms. But if i remove time.deltaTime i go like a supersonic
What should be put instead of time.deltaTime
And what did I do to unlock it from 60 fps to 800 fps, since I got this problem
You don't put anything instead of it, you change the sensitivity value to something much smaller to compensate
!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/
📃 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.
Just the mouse rotation is like that or i shouldnt use time.deltaTime anywhere?
It depends on the use case
Lets troubleshoot a bit because i dont get a thing. I have 800 fps in the game editor but in the game only 60fps. I builded the game like 10 minutes ago and I had 2000 fps in the builded version, but now after starting another project, builded that, now on this project the build version stays at 60fps. How can I change that and why does it change automatically.
Like how to cap the fps or how to uncap the fps
The settings related to that are vsync and target frame rate. Look up how to set or unset those
Now it doesnt even move in the build when its 60 fps and on the game editor, its moving perfectly fine.
Ill
you shouldn't use deltatime for mouse input
you should use deltatime for turning per-second stuff into per-frame stuff
so i'm trying to make producer1 make points and producer2 make producer1 but when i tried to make the incomePerInterval increase with the Prod1nr but it just took the points and stopped making points passively
From a quick glance I saw you have a function within a function, you have void UpdateButtonText() function isnde your Void Clicked(). You should separate the two functions
didn't even see that
but it seems to have broken more things
now it shows me it passively make points but doesn't make it and now the interval stopped working entirely
Hard to tell when we don't have the context on how the PassiveIncome works
Don't you have the ProdInr set to 0?
warnings are not errors. and that warning is pretty self-explanatory
have you actually saved the code? also stop sending screenshots of code. see the bot message below for how to correctly share your !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/
📃 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.
btw can some explain what is time.deltatime?
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Time-deltaTime.html
The interval in seconds from the last frame to the current one
that's literally all it is
it's a conversion factor between frames and seconds
ah i see, thanks @slender nymph
thanks aswell
is this smart
Well it does a thing
depends on what you mean by "smart", but there's no real issue with it i guess?
looks fine. Maybe use delegate type if you want named params
thanks
i dont know what a delegat type is
i meant if this is how th e professionals do it
egdelegate void DamageDelagate(float damageAmount, Vector3 point, DamageType damageType);
Action is a type of delegate too btw (no args / is void return type)
thankyou nav
I advise you to use the event keyword to make sure only Limb can invoke the event
sorry i just got around to implementing this but just realized..what am i supposed to attatch the monobehaviour to?
abstract classes should be inherited from, they don't themselves go on the gameobject
yeah i just dont fully understand they're code yet
like for example a monobehaviour has to be attatched to something but when its just in my inventory its not like theres a prefab of the item so what am i attatching it to?
not sure the exact context so cannot say, you'd have to explain abit more what you're doing
im making an items system for my game and they reccomended doing it like they're code up there, i just dont understand whats going on
idk i just cant comprehend how im supposed to do this
like the structure
have you done a basic system already ?
no
I would suggest you start small, and build your system up that way
im trying and ive run into a roadblock
its easier to learn from your own mistakes and find out where the pitfalls are
well one issue im running into is that i cant assign static fields of non monobehaviour scripts in the inspector
you really dont need to set it up the way you were shown there
in what way do you need static for your item system?
i meant more like, what value are you using it for?
just dont mind that lets start from the beginning
im just completely lost on the overall structure of how to set up the item system
like what should each item be? a scriptable object? monobehaviour script? prefab?
i cant figure out how to make it work
follow the KISS principle 😄
dont worry about the code yet. the first thing you should do then is think about what you want items to actually do. To you, what is an item system? what does the user see, how do they interact with it?
anyone ever ran into this bug where something like float just sets itself to 0 magically, my third field does that rn if I swap places it with something then whoever is third still resets even with 0 refs to it and not serialized lmao I actually remember getting this like year ago so im gonna ask again anyone know what im talking about and did you solve it?
A variable does not change of its own volition. Something is setting it.
pretty muck exactly like minecraft - they can store it in their inventory, use it, drop it on the ground
You could make the variable private and see what throws an error
I have a vid to prove it if you give me a sec to upload it
or turn it into a property and breakpoint on the set
going back to this im just trying to figure out the best way to represent each item
simple Scriptable Object system might work here..
done such a system before including recipes and works great with SO
thats what i was thinking but what about things like durability and other iitem specific vars/
POCO for the modifiable stats, copy them from SO as base stats then modify them as you wish
poco?
plain c# object (like class)
(Plain Old C#/CLR Object)
thats what i was doing
@polar acorn
so then do i make it so for each item i make a new SO of the base item SO and a new subclass of the base item poco?
tried without attribute after filming
also you can see in rider "unchanged" or whatever value it is
if I set it in inspector
i wanted to do that but then how do i give each poco a reference to the SO?
ok so you want items that can be used and every item presumably can be dropped. items will be used in different ways, so that means you'll need inheritance to define the Use functions in derived classes. Your base item class right now seemingly just needs an abstract Use method and possibly a virtual Drop method if theres a chance a deriving class could change its behaviour
A scriptable object is simply used as a data container. You would use it to store values and pass it to your objects. Your items would likely be represented as monobehaviours in the end.
you're getting a bit too ahead here. first worry about setting up the foundation of your item system before worrying about something you can't even do yet
i did
i made an inventory system, slot system, etc
next step is making it so actual items are passed around that inventory and slot system
yes sorry
Remove the serialized property, then rename the variable, and try again
inventory: https://hastebin.com/share/ugulocequt.csharp
item slots within inventory: https://hastebin.com/share/ulegatihof.csharp
item SO for data shared between the same type of item: https://hastebin.com/share/qutemecisu.csharp
item poco: https://hastebin.com/share/zewalonilu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you really shouldnt worry about the UI either yet imo. That should come way later. Anyways the UI is just a matter of slapping a sprite in your scriptable object, then reading that when needed
so should i like delete and start from the beginning?
that wouldnt be a huge deal
you don't have to delete everything
what i usually do when i have to remake a system is rename the folder for that system with an extra underscore, and then create a new folder for the new version
then you can copy over stuff that doesn't need to be remade, or see your previous code for reference if needed
remaking a system doesn't have to involve throwing out all the work you did
and you can also delete stuff you've already recreated to see what you have left to remake
why do i have to remake it though? like i feel like the item system i had planned was pretty close to what u guys are suggesting theres just some stuff in it i dont understand
for example, how do i give the poco a reference to its so if i cant serialize base c# scripts?
oh uh, i just got here. idk if you have to remake or anything like that, i haven't been following 😅
i just mean if you have to remake, you don't have to delete the entire thing all at once and start over from scratch
not delete but i just wouldnt worry about continuing the UI side for now
ah yeah good point
the poco is just the data on the GameObject for modifiable stats
the SO just defines what type of item it is
poco doesnt care about the SO itself
i was trying to represent items as pocos instead of game objects for the sake of moving it around in inventory and stuff
keep it simple, it will be easier to deal with tangible gameobjects than pocos for the item itself IMO
Feed the stats from POCO and SO to the gameobject (another main script) then deal with the logic there and other things like moving it around or creating new ones
what game object?
the first major thing i notice is that your UI stuff is intertwined in your inventory. you'd probably want to reconsider that. if we're comparing this to a minecraft inventory, well npc's can have items too. They dont have a UI. Then your inventory doesn't really have anything in regards to using items.
your item class also doesn't have a method for dropping. It should likely reference a prefab from the ItemSO to be dropped so you have a visual model on the ground.
The ItemSO doesn't make much sense for why you need a reference to the player, or why its static. that 100% should be removed in any case.
like an Item gameobject
for example. Different game type but same concept/idea.. If I have a Card prefab, it just needs to create itself from stats in an SO and Poco, then anything modified (the copied POCO stats) is on that specific Card instance
this is getting too confusing ill prolly remake it
In a "minecraft" style.. Imagine SO is saying "this is wood"
Poco is "we copy base Durability of 10" to put on our actual Item gameobject , then we can -- Durability on the copy of poco stats
the gameobject is the glue that holds those together, the tangible object you can move around copy/modify stats from, interact in the game world etc.
still i dont see why we're worrying about the SO when the item class right now has 2 fields and 1 out of 2 methods they want.
The first thing you should do is make your foundation. An item class that can be used or drop items. It doesnt matter right now if the use or drop does anything. Put debug logs in there that say "dropped from game object name".
Make a collection that holds your Items and have a way to Use or Drop each item. none of this should involve UI yet
wait rewind
so items are a poco?
cause nav says it should be a monobehavoiur
or a gameobject?
idk i dont understand
Item could be a MB if you want it to
MB just makes it easier for example doing Pickups and stuff in the game world
i was thinking every item is its owned selfed contained, nonmonobehaviour, non game object, etc, just a so or poco or something
its up to you if you want to make it a poco. i think it makes sense to do. When dropping an item, you would just spawn a prefab.
then for example for dropping stuff, i just make a generic dropped item prefab that takes in one of these self contained item things and then displays, its icon
yeah exactly
thats what im trying to do in my code
the player ref is spaghetti code ill delete that
the problem with that IMO is you have to spawn a gameobject everytime you drop something
instead of just hiding one you already have in inventory
ok i think thats where the confusion was coming from we were thinking about it in completely diff ways
thats kinda how i want to do it though i want to make every item more abstract in a way that it can be passed around in many diff forms
it ultimately comes down for whats easier for you
if you think one way is easier to work with use that
for example should every item in a stack have its own gameobject?
alr so thats where im asking for help, first of all, how can i give every item poco a reference to its so?
thats why i just store the gameobject already instanced and hide the gameobject, but thats Easier for me, it may not for someone else
the dropped item should be a different gameobject regardless
if drop and pick up the same item , i would see no point in Destroy/Instantiate every time
also with this first point idk what you mean by ui intertwined with inventory. like for example for npcs id just give them like an array of items then take the item out of that array and put it in the players inventory when sold, for example
the dropped item will usually have a collider and fall until it hits the ground, might spin around, might be smaller, etc etc. none of this logic needs to be on the object held by the player
ok idk why were still debating this id like to go with bawsi's structure if thats ok
it makes more sense to me
for npcs id just give them like an array of items
like an inventory
yup the inventory i have coded in here is purely ui
right?
I mean..we're pretty much saying similar thing, just difference in how they are instanced
Once I instantiate a "Wooden Axe" from the SO recipe its a gameobject with its own Stats poco, if you pick it up, (in my case it wont destroy it) just hides it and puts it in the array of items for later
like i can sorta see where ur coming from but even an individual player and an npc would have very diff types of inventories
yes, you should rename that to make it clear its for UI, and then have an class which is just an array of items. This would be your actual Inventory. Your UI inventory will need to read from the inventory, and possibly call functions on it
this inventory prefab i created is for chests and the player
i just dont get why i need that extra layer of abstraction
(i think thats the proper term)
its not a layer of abstraction. your inventory is not different from players to npcs, or even chests. An inventory is an array/list of items, that's all. there is no different type of inventory here
This would be like if you had a class called EnemyHealth and PlayerHealth.
the UI should be separate entirely because its only for your user. this is why you also make it last because it's going to be interacting directly with your inventory
yes UI is def not something you should even have in your mind right now..
and if you designed it around UI at all, go back and redo that
Anyone knows why this aint working? I already have another working event but this one doesnt work for some reason, names are all correct idk what the problem might be.
public class Scoreboard : MonoBehaviour
{
public Text txtScore;
int score = 0;
void OnEnable()
{
GameEvents.current.score += SetScore; //error here: object ref not set to an instance of an object
}
void OnDisable()
{
GameEvents.current.score -= SetScore;
}
void SetScore(int points)
{
score += points;
txtScore.text = score.ToString();
}
}
Here is GameEvents
public class GameEvents : MonoBehaviour
{
public static GameEvents current;
private void Awake()
{
current = this;
}
public event Action<int, Vector2, Color> vfx;
public void SpawnVFX(int id, Vector2 pos, Color color)
{
if (vfx != null) vfx(id, pos, color);
}
public event Action<int> score;
public void EditScore(int points)
{
if (score != null) score(points);
}
}```
well most likely that OnEnable is running before you assign current
SpawnVFX works fine though...
ok ill move my current folders somewhere else and restart
ill post the code as i go to ensure im doing it right
if thats ok
i guess i can put it in a coroutine to wait a second
that doesn't change what I said, if they have the same execution order its not guaranteed which one will run first, usually created instanceId
for singletons and you want to use OnEnable for others needing that singleton you could just modify the execution order of singleton
this worked but yeah ill look into singletons, that sounds more efficient
you already using a singleton lol
I just suggested you change the order of execution for it so you dont have to do some hacky shit like delay 1 second..
yeah but i just got that from a tutorial
yup this works better 👍 thanks
item: https://hastebin.com/share/bumomovomi.csharp
item so (data shared between items): https://hastebin.com/share/pogapaguze.csharp
inventory: https://hastebin.com/share/kahuqujuci.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@eternal needle is this what you mean?
Quick question: what does POCO stand for? 🙂
plain ol' C# object
really something you could google lol
Ahh, thanks
the C may change and may stand for other things
I tried, gave me everything but that
POJO is a related term for the same concept in different languages
yea if you want to go the poco route then this seems fine so far. youd still need to add logic like the constructor and setting up that items array so it isn't null.
ok so say im making an item Apple so i make a subclass of that base item class and a new Item scriptable object for it - how can I assign the itemData field of the item to the new SO i made?
pass it through the constructor when you new items. anything that wants to create an item can take a reference to the ItemSO
the only thing that might be awkward here is setting up items that are held by the player or used in animations.
what if i make an item database that has a ref to every item so and constructs items and auto passes through the SO? also i can give each item so an instantiatable prefab that can be controlled by the normal item class
kinda like navs idea
so like
class ItemDatabase : MonoBehaviour{
[SerializeField]
private AppleSO appleSO;
public Apple ConstructApple(){
return new Apple(appleSO);
}
}
that might be kinda overkill since every item would need a construction method but you get the point
you might end up having an item database anyways because of needing to save inventories based on ID. Im not so sure how you'd want to handle spawning different items because it depends really how they're spawned
Why not have the SO create the item ?
And a list of SO which you can all call the same function "Create".
oh yeah that works
wait how can i give an so a method
or like define it when i make a new type of that so
if that makes sens
You could make the SO abstract, if you don't have too many variations of it
itd just be another method to override.
public abstract Item CreateItem();
abstract if you dont want to be able to create just the base item class
how can i override it? when i make a new SO of the type ItemSO i there isnt a script, just parameters that i can set
in a deriving class, like how you would have AppleSO in that example above.
public class AppleSO : ItemSO then override the method
so im making a scriptable object template for every item then only using that template once?
isnt the whole point of scriptable objects to make one template and use it multiple times?
Can the Create method in the SO find out what it needs to know from the fields in the SO? Or does it absolutely need specific code that will change for every kind you make?
? i dont understand what you're asking sorry
ohhh wait i get it
i mean i could do a name based thing
its a data container, you can use it multiple times but its not like a requirement. if you have multiple apples that heal different amounts, boom you've now reused it.
ooh wait maybe i could make it so theres like a food scriptable object and use the same so for every food
from how i see it, you'd be creating a new SO class everytime you have to make a new Item class, which would only be when you need different fields or different use/drop functionality
so every item class doesnt necessarily need to be just one item
so yea maybe food could be one class
and then stuff with functionality thats too special to generalize can just have its own so
and its own item class
yea sounds about right. i suspect you'll have quite a few item and SO classes that just have one item "template" associated with it but that really isnt an issue. its just game design
in the minecraft example at least, each tool (shovel, pickaxe, etc) would have a few different SO assets because of the different types like wooden, iron, diamond
Hello there
i had an idea what if i take it even further and make it so each item can implement multiple types of so's
so every item has the base item so instance with basic info all items need
but food items also have a reference to a food so with info on how much it heals
ok ill figure this out
Tysm for everyone’s help
Oh wait that’s what you were saying here lmao
how can i have my own methods have something similar to this? ( the method description )
<@&502884371011731486>
99% chance of malware
bot missed it 👍
yipee thanks
Well, the first one is certainly solveable
okay.
we’re talking about the warnings here.
yellow
basically
Hey is their any unity prodigys in here looking for help
the yellow ones disable me from testing playing
no they don't
the compile error does
Look at the line the error is on, and fix the syntax
I just want a scroll view to show some images on a menu via a script and its annoying me i asked ai no solution was found
Add a layout group to your scrollview that will automatically lay out the images as they get added, then instantiate Image objects as children of it
It'll position them automatically as new ones are added
Yes that part is working but i was trying to make a script to just throw a ton of images in their
So spawn a ton of Image objects
Like i select them in a unity script like a image and it just throws them in
How would i do that im not very good at coding
Make a list of Sprites, loop over it, and for each one spawn an Image prefab and set its sprite to that one
I was using this and it wasnt doing anything so i scrapped most of it to retry
Ye im being quick while highlighting it my other account on my pc is seperate because ive been tokenlogged and it was horrible
And ifs just awkward to send one to my phone in rapid speed
2025 there should be no reason take a photo of what a screenshot can solve
Just trying to get some quick revive help for a silly project to pass my course
you have a course and what did they teach you any of the material ?
They tought us barely any unity gave us the thing and said play along with it and figure it out college was such a awful idea
And then handed us this giant assignment to make a detailed idle game for a phone
do you at least know how to setup the code? like loops and instantiate stuff ?
Little bits i have been using ai to learn and help me through confusion and guide my steps
Even if it is controversial it can be a good learning help
Its just a learning agent for me once i learn my way and get it burned into my brain i can move it away
Are you using it to write your code?
Im trying to rely on it as little as possible
most people don't use for learning though they just copy the code and not understand any of it lol
Guiding my way if i need to use it
Having it breakdown to me what stuff does in coding lol
Havent used C#
Before we have done bits of python and scratch at college its embarassing
Well someone has already given you the answer on how to accomplish your task. I would, if I was you, write that solution in commented form then go about accomplishing it one step at a time.
scratch can be very useful..especially teaching breaking down ideas into coding logic
I appreciate the help i also assume it would be possible to only make the images appear under a logic if so and so is collected
Its going to be near impossible for us to help you code if you don't even know how to code to begin with...
No intention of being rude, or question your experience, but were not going to copy paste code for you.
find out how to do each one, individually how you solve any problem
I would just like to if its possibe in unity to make something from a scroll view to do thay
That
Im not asking for you to write me the code
If you're in a college program, I suggest reaching out to your professor and asking for some guidance. If its supposed to be done via coding in C# than you should have a companion course teaching C#, otherwise the method to solve your issue is probably achievable another way.
Unfortunately he is useless ill have to reach out to my older friend who codes for fun to see if he can assist in my trouble Thanks 😅
You really should get some guidance, because if you're expected to do a C# assignment with no courses or direction, than you're not really learning anything.
everything is possible
Hello, I'm doing my very first project and my character just falls into the void. I want him to not have gravity affect him at all as I'm doing an orthographic thing. I have some script for its movement that my teacher sent (I cannot ask them for help they do not answer) and every time I press the assigned movement keys this error appears (There's also pictures of my character made into a prefab, the input manager, and my script):
holy color scheme batman
you need to get your !IDE configured because you have a bunch of issues. also that color scheme is god awful
bro is in the matrix
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
Help would be greatly appreciated, I do not know code at all, I'm an artist, I did not sign up for this 
having a configured IDE will help you immensely
having configured tools is a requirement to get help here, so do that first
what is that?
so like visual studio?
-# fyi nav you can shift+click reactions so the menu doesn't go away
ok, how do I get visual studio configured? At the very start it asked me to install a unity developer package and I did, what else should I do?
follow the rest of the steps linked to you
also the error you showed in the screenshot, has probably nothing to do with your code not working, one thing I will hint you towards.. C# is case sensitive..
Why does my camera bob go crazy when i look up and when i land it glitches
void CameraBob(float Speed)
{
if (!isGrounded) return;
if (moveDirection.magnitude <= 0) return;
if (Vector3.Dot(moveDirection.normalized, camTransform.forward.normalized) < 0.99f) Speed /= 2;
headBobTimer += Time.deltaTime * (Speed / 2);
float bobPos = originalCamYPos + Mathf.Sin(headBobTimer) * (2/ Speed);
camTransform.localPosition = new Vector3(0f, bobPos, 0f);
}
yeah is what i'm seeing, visual studio was already set up like shown in the tutorial sent
we can see that it isn't depsite your god awful color scheme
what makes you say its configured ?
Go type some random gibberish into the script. Is it underlined in red?
it looks exactly like in the screenshot of the documentation
the preferences I mean
I will try that, give me a sec
hmm actually it does not
but inside the editor we can see for example its not underlining your missed capitlization
Then it is not configured. !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
okok, I will read it more carefully now
if you did all the steps in Visual Studio page, also https://unity.huh.how/ide-configuration/visual-studio#if-you-are-experiencing-issues
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
esp the Regenerate part
How do I go about creating a power meter like this?
https://youtu.be/_z0mx3pgEs0?si=881tu7q90eXtIYNE
Tekken 7 Bowling All strikes in a row.
You can use Image component on UI then set it to Fill mode and control value via code (the value here is 0-1 so you would currentVal/max )
the value is very basic stuff in Update using += deltaTime * increaseSpeed etc.
its a pretty basic mechanic
Is there anything I could read/watch?
idk any specific video
something like
if(KeyHeld && someValue < maxValue)
someValue += Time.deltaTime * increaseSpeed```
You probably dont need the keyheld if its just controlled byitself to hit it at specific time
Also what do we call these? Time event bars?
Thanks, I'll try
Why does my camera bob go crazy when i look up and when i land it glitches
void CameraBob(float Speed)
{
if (!isGrounded) return;
if (moveDirection.magnitude <= 0) return;
if (Vector3.Dot(moveDirection.normalized, camTransform.forward.normalized) < 0.99f) Speed /= 2;
headBobTimer += Time.deltaTime * (Speed / 2);
float bobPos = originalCamYPos + Mathf.Sin(headBobTimer) * (2/ Speed);
camTransform.localPosition = new Vector3(0f, bobPos, 0f);
}
be patient if someone knows the answer they answer , no need to post it again right away..
its cause theres alot of messages now so i wanted people to see
cause it got hidden in a way
its not that bad..people still do have scrollbars
idk i just wanna fix this and sleep 😭 its 12 am
start by debugging your issue instead of just throwing hands up and hoping someone has answer right away
ive been trying
get rest first, never good to debug tired
i started coding yesterday btw 😭
you have plenty of time ahead of you, its easy to burn out like this
I spent my whole 2 days trying to fix screen tearing due to 1 settings 💀 I was so annoyed that i lost 2 days js cause of that
there is some values you could debug and see why they are different at specific times
In mathematics, sine and cosine are trigonometric functions of an angle. The sine and cosine of an acute angle are defined in the context of a right triangle: for the specified angle, its sine is the ratio of the length of the side opposite that angle to the length of the longest side of the triangle (the hypotenuse), and the cosine is the ratio...
its part of the job lol
you put radians and gives you value between -1 and 1
these functions help with giving it some motion
No, we have a function for that and it's called absolute value
Oh 😭
Ig i have alot to learn 😭
is moveDirection a Vector2?
Vector 3 from what i remember i use rigid body force
what do I do here? step 3 tells me to go to the add button, there is none
How can a client destroy a game object that was instantiated by the host?
install editor
Whatever you think it does not show the line. 😭
in UNITY2D, how i can make an Object move at a position i want?
for example, we have a Boss, is like an enemy, it has the same enemy programation/script of following the player POS by trying to make their POS into the player POS. but
the Boss inside a function has to Jump, and Slam down, and also, the Boss has to inside another function has to Run a lot o the right, and a lot o the Left. How?
i should use Add-Force or smt?
you dont need any of this..what are you trying to do ..
following the directions in the page
this one
but you already have visual studio & unity editor, why are you on that step..
the editor is there, you need to just verify the Unity workload is there in VS Installer.
if all those are done and still having issue then I linked you already to troubleshooting page
@eternal needle sorry super late but quick question, can i give the Item class a static variable holding the player assigned by a game manager so each item has a ref to the player
Just make the player a singleton. But the items needing to know about the player is a red flag.
how come? when an apple eaten its gotta heal the player no?
The player eats the apple, so it heals itself based on the apples properties. The apple doesn't know it gets eaten and then tells the thing that ate it what to do.
The authority lies on the player to make those decisions.
so if an npc eats an apple, it should heal the player? at most all you would need to do is pass a reference of whichever character used the object, and then call a method on that character
this still doesnt change from before where we said static makes no sense here
ok but for example and npc doesnt have hunger, only the player. do i still need to give the npc a restore hunger method just so that its compatible?
You could check the type of the character. If it's an NPC do nothing. If it's a player character, call the desired method.
If npcs don't have hunger, don't implement the hunger stat and methods in them.
Ideally, you'd have some kind of Stats system where you can dynamically add or remove stats from characters.
Then when an item is supposed to restore some stat you check your stats collection, and if the stats is not there you just ignore the effect.
so maybe like a self contained stats monobehaviour
so a base stat monobehaviour with like a value, add, and remove method
I'd make it a plain class, but it depends on your project I guess.
how would i attatch that to entities then?
like a monobehaviour component with a list of stats that i can add to?
You would have a list/array of these stats on a character or stats controller/manager.
is there any advantage to that over just making them monobehaviours?
It's neater and easier to extend. You can have hundreds of different stats this way. Imagine having hundreds of component on a go.
ok so maybe like every entity has a monobehaviour that extends from a base monobehaviour containing an array of stats, so that each entity can add its own stats in Start()?
or maybe theres a way to serialize it?
so that each one can have the same component
wym by this
like make it so that theres a monobehaviour with an array of type stat so that i can drag in the base c# stat scripts from the inspector
i just realized that naming was confusing
1 thing im gonna nitpick because a lot of people do it, the word instance and class aren't interchangable with script, you'd never be dragging scripts anywhere
with base classes, you can't really drag and drop them like that. for various potentially good or dumb reasons Unity isn't the best when dealing with base clases in the editor
oh i was hoping that it would automatically instance it
you can serialize them in the editor in general though, by putting [System.Serializable] on the base class itself
and usually you want to use [SerializeReference] on the field that's storing the instance of the base class
so say my poco is the class Stat, I would put [System.Serializable] in the poco and then in the monobehaviour component attatched to each entity I would put a [SerializeReference] Stat[] stats then drag the Stat subclasses into the stats var?
So this is the bad part about base classes and unity editor stuff
you can do all of that except for that last part
you can't drag base classes in any context
and you can't select what type they are
if you have Stat[] stats it will show you an array of stats that you can add and remove from
but you can't say like oh this one is gonna be this inherited version of Stat
there's no type picking
so what should I do?
Couple different ways people go about it.
There's quite a few third party solutions that introduce ways to type pick base clases like that on github, asset store etc.
There's also some solutions that can be made where you basically have a scriptableobject per stat type and that scriptableobject has a function that can create and return said type, and you use a asset of that SO to drag and drop, create them etc. . this solution works abit better if your comfortable with generics
this feels a bit excessive
realistically an npc is never gonna use an item
and realisitcally nothing other than the player is gonna have a stat other than health
At the end of the day no one here can force you to pick a solution, You know your project more than anyone and can choose what route to take it. Ideally responses here just help you make a more educated description 😄
I get that but also it just kinda feels like whenever I ask a question instead of answering it, people say “actually you should do it like this” and then just dip so it takes forever to figure out what they actually mean
Like it’s already been an hour and 40 minutes and I feel like I still don’t have a concrete solution nor an answer to my original question
I get that too but it also feels like whenever I try to make something myself I end up messing it up, coming here, then trying to restructure the whole thing
Is your game RPG or RPG-like?
There isn't a concrete solution. There's many ways to achieve the same thing, just depends on time, knowledge, intended effort, scope, limitations etc. etc.
Hello there! I am just trying to put some code in for a Health UI/Hearts, while following a Tutorial. I got the little Heart Meter in (3 Hearts total) but for some reason it only takes 1 damage, and only to the middle heart.
This is going nowhere I’m just gonna take a break and come back later. It’s like every time I run into a problem i just go deeper down this rabbit hole. Maybe I’ll restart from the beginning again with a diff method idk
How are you investigating/debugging the issue?
I was just trying to compare the code I made to the code in the tutorial, and it LOOKS identical, but the results are not. I do know the Tutorial is based in an earlier version of Unity. So I figure it might have to do with that? But I cannot tell.
- If the code is exactly how it is in the tutorial, then it's likely some setup in the editor/inspector/scene missing. Make sure you didn't skip any steps there.
- Make sure you don't have errors(and possibly warnings) in your console log.
- Learn how to debug issues. Learn about debug logs and visual debugs and how to use them. Log important info where your logic executes to make sure that it does execute and the relevant values are what you expect.
- if you need further help, share your !code and a link to the tutorial.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 did not SEEM like I did. I watched this section of the Tutorial ~3 times, checking each time.
- No errors, but I did have 2 Messages?
- I am definitely interested in this.. but I think I am a little too shitty at this to know where to start heh.
- Certainly. I had two different pieces of code this could interact with, and here is the Tutorial Link to the time I am at: https://youtu.be/Pkc4A1ukbJU?t=5224
First Related Code Thing: HealthUI
//using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthUI : MonoBehaviour
{
public Image heartPrefab;
public Sprite fullHeartSprite;
public Sprite emptyHeartSprite;
private List<Image> hearts = new List<Image>();
public void SetMaxHearts(int maxHearts)
{
foreach(Image heart in hearts)
{
Destroy(heart.gameObject);
}
hearts.Clear();
for (int i = 0; i < maxHearts; i++)
{
Image newHeart = Instantiate(heartPrefab, transform);
newHeart.sprite = fullHeartSprite;
newHeart.color = Color.red;
hearts.Add(newHeart);
}
}
public void UpdateHearts(int currentHealth)
{
for (int i = 0; i < hearts.Count; i++)
{
if(i < currentHealth)
{
hearts[i].sprite = fullHeartSprite;
hearts[i].color = Color.red;
}
else
{
hearts[1].sprite = emptyHeartSprite;
hearts[1].color = Color.white;
}
}
}
}
By the end of this video, you’ll have everything you need to create an complete 2D platformer game in Unity! 🎮 This tutorial covers all features like character movement, jumping, enemies, collectibles, and more. Perfect for beginners and anyone looking to improve their Unity 2D game development skills!
Whether you’re building your first ...
Second Related Code Thing: PlayerHealth
//using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public int maxHealth = 3;
private int currentHealth;
public HealthUI healthUI;
private SpriteRenderer spriteRenderer;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
currentHealth = maxHealth;
healthUI.SetMaxHearts(maxHealth);
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy)
{
TakeDamage(enemy.damage);
}
}
private void TakeDamage(int damage)
{
currentHealth -= damage;
healthUI.UpdateHearts(currentHealth);
StartCoroutine(FlashRed());
if(currentHealth <= 0)
{
//player dead! -- call game over, animation, etc.
}
}
private IEnumerator FlashRed()
{
spriteRenderer.color = Color.red;
yield return new WaitForSeconds(0.2f);
spriteRenderer.color = Color.white;
}
}
- Start from understanding the problem. What does it mean code wise that "the heart meter only takes 1 damage and only in the middle"? Where is the code that should deal the damage? Does it deal the amount of damage you expect? Log it. What code is responsible for modifying the visuals(disabling ui or something?)? Does it execute correctly? Does it apply to the correct objects? Log the relevant values.
My immediate thought was it was the 'HealthUI' one somewhere, since that is probably how it looks, being the UI. And in the end of it I think it specifically addresses 'currentHealth' and putting in empty heart sprites. But I can't see anything wrong.
Why is this using 1 here? Is it intended? What's the intention behind it?
hearts[1].sprite = emptyHeartSprite;
hearts[1].color = Color.white;
Oh! I doubt it is supposed to be. So yeah, looks like an error. Let me see if it fixes then! And yeah, ti does. Because the 1 would then be the 'second heart' right? 0-1-2? (I think I am understanding!)
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
yes arrays are 0 index so 0 = 1st
Thank you both very much! That indeed was the issue. Now I can move onto the next part. XD I swear, this 3 hour tutorial is going to take me 15 or so hours total hahah. But it's worth it! I'm definitely learning.
hey all:
destroying gameobjects should be the last resort, is that right? especially for ui elements?
It's not quite that black and white
Most of the time there's nothing wrong with disposing of objects that aren't needed anymore by destroying them
absolutely not what this server is for
Not a code question
!warn 619005684557545472 Keep it relevant to the server
soulcelestial has been warned.
you can code in $0 with the pinned resources
If you're instantiating and destroying objects a lot (like in a SHMUP with all of its bullets), that's one example of an instance where you don't want to be doing that, because those two methods are very expensive
People do object pooling in that instance
thank you :)
do loadscene by additive benefits from async/coroutine loading?
i use loadscene.single most of the time because i only need to switch from scene A to scene B
wdym by "async/coroutine loading" and wdym by "benefits"?
we use async or coroutines to load a scene because switch from scene A to scene B might need to load tons of stuff, so we pre-load the scene using async beforehand, and maybe we include some cinematics or loading animation to cover up the loading, once its loaded we just jump to other scene
thats the benefits right?
but what about if we load scene by additive?
you don't use coroutines to load a scene
additive just doesnt unload the active scene
Hey all! I'm new to Unity (I've used other engines in the past) and am losing my mind with a simple issue.
I have a 2D project. I've added a sprite with a box collider 2d and attached a script with OnMouseDown implemented. No matter what I do I cannot get this to actually respond to mouse events
using UnityEngine;
public class box : MonoBehaviour
{
void OnMouseDown()
{
Debug.Log("Clicked");
}
void OnMouseEnter()
{
Debug.Log("Mouse enter");
}
}
Am I missing something obvious? I think this should be all that's required to get a sprite to react to mouse events right?
I've tried changing the include/exclude layers on the collider, adding a rigid body, changing the collider size, etc. No matter what I do I never see the mouse events happen
Those are outdated
Look into IPointerDownHandler and IPointerUpHandler
The ones you're trying to use don't work with the new input system afaik
(you will also need to put an Event System in the scene and a Physics Raycaster 2D on your camera)
Hey! What is the differences between using Rigidbody vs not for character movement? (working in a 3D environment)
Rigidbody is simulated in the physics engine
I'm not sure what alternatives there are to rigidbody but I know character controller has .Move()
What are the upsides with this?
It behaves like a physical object
what alternatives are there to creating movements than rigidbody then?
Thank you @wintry quarry! That fixed it. It's wild that I didn't see anything about this when googling. I was only seeing references to the old system. Is this a relatively new change?
If you consider 8 years or so to be new
its overwhelming. What are the "conventional" ways for making a character move?
I'm not sure what you're actually trying to ask here.
I think what you should do is follow a few different tutorials that use different approach (Rigidbody, CharacterController, KCC package) and get a feel for them maybe
But you're just going to have to try a bunch of ways to understand
Also note that "make a character move" is extremely vague
Every game has a unique idea about what that means
There are grid-based strategy games, platformers, physics puzzlers, etc.
yeah, I want to research and code some things, and since I'm pretty new I wanted some orientation
I'll look up documentation about rb's cc's and kcc
ty
Hello
I have this little line of code here:
`BodySprite.transform.localRotation = Quaternion.FromToRotation(Vector3.up, walkNormal);
walkNormal is the normal of the surface that my body object is scanning with a hitscan
the purpose of this script is to turn the player body facing according to slopes etc. on a surface
my problem is: If i turn the camera 180° around the character, the sprite rotates with my camera object
and then if I walk up a slope, it is adjusted to the slope- however oddly enough mirrored by the Z axis instead of just being aligned to the normal
why does this happen? Quaternion should organize the facing in 3D space based on 3D space core coordinate system no?
are you working in 2d or 3d
Would the following works ?
BodySprite.transform.up = walkNormal
3d; but the character is a 2D sprite
Good idea, I try it
so what's up with having sprites?
ah
sry xD
are they sprite renderers or what exactly?
no they are sprites
also what's the intended view if you look at this scenario straight-on, like, 90°?
just 2D figures having a good old parapppa the rapper time in 3D land
yeah but what components are you using
sprite renderers or images or some other third thing
oh yeah they are sprite renderer components
thats the main problem, its a 360° orbital cam
yeah the sprites would turn into lines in that scenario, right
it has a limited up and down angle and cant go lower than 0°
yes
So all in all the sprite is rotated with the camera
yeah that's why the 180° scenario doesn't have it rotated
BodySprite.transform.up = walkNormal works great btw but now it has the issue where the sprite turn to lines
Is it supposed to be a billboard?
I suppose what I need is a method that sends raycast fromt he camera to the surfaces too
you said 360 orbital cam buit these are sprites, right?
So are the sprites supposed to billboard?
yeah but only along the Y axis
if you move up and down, there is a bit of a limit on how far up the camera goes
so the sprite will just be seen in a bit of "depth of field" squishing, revealing its 2D-ness
that is all intended and good
Ok so then like...
Vector3 camForward = Camera.main.transform.forward;
camForward.y = 0;
camForward.Normalize();
BodySprite.transform.rotation = Quaternion.LookRotation(camForward, walkNormal);```
this should do it i think
yes, for the billboarding
normalizes to (1,0,1) ish
how does the Quaternion.LookRotation() work?
It takes two vector 3
yes the first one is the resulting object's blue (forward) vector
the second one is its yellow (up) vector
ok
since it's a sprite blue should be facing away from the camera
huh thats cool af
hence using the cam forward
Quaternion is defined like this right? One forward and one upward vector (base vector)
Yeah
It works
Thank you PraetorBlue for sharing this method (constructor?) for Quaternions with me
It solves the entire issue with these 5 lines of code
Absolute Cinema
Awesome, glad to be of help
To understand this for the future, the Quaternion object is created and then inherited into rendering?
I only know the term constructing from object based programming
Quaternions confuse me and overwhelm me lol
It's not technically a constructor, but it behaves exactly like one
Unity could have written this as a constructor if they wanted to
we are constructing the Quaternion object after all, just with a descriptive name.
Quaternions are less confusing when you think of them just as a piece of data that represents a rotation
similar to how a Vector3 is a peice of data that can represent a position
yeah
you don't need to worry about what's "inside" so to speak, it's not important
I thought Quaternions are essentially a Vector3,Vector3,Float
they're stored as just 4 floats
where the first attribute is the location, second the rotation, and then there is a scale
no, you're maybe confusing Quaternion with a Matrix4x4
Quaternion is just a rotation
alright
Matrix4x4 can store position, rotation, and scale
Ooooh I think I got it
its a rotation but vector-like
instead of having a fixed 360° clock
so if I want to turn to the right, I go: (0,1,0,probably Pi?!) Turn me around Y, for this and that amount
Like I said, don't think about the actual internals and numbers of it
it's complicated and not really important
ok 
if you want to rotate around the y axis you can just use those "constructors" Unity provides
e.g. Quaternion.Euler(0, degreesToRotate, 0)
that creates a quaternion that rotates that number of degrees around the y axis
Quaternions literally use imaginary numbers. It's a four dimensional vector in the complex-real space.
Do not attempt to make sense of how the values of a quaternion translate into anything tangible
https://quaternions.online/ but as said. don't worry too much about the 🪄 of it all 🙂
see 3b1b's video on visualizing quaternions to see how mindfucky they are
and then decide to treat them as a blackbox from then on out
void Awake()
{
private Tilespawnner tiles = FindObjectOfType<Tilespawnner>();
private GameObject[,] tilearray = tiles.spawnners;
}
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
* tile = tilearray[x, y];
if (y < maindict[GameObject.Find(dragged.ToString())][2])
{
tile.tag = "Opened";
}
}
}
``` I got null reference exception at * line but i don't know the reason why I got it. When i debug the line, it is not debugging.
Well, for one this wouldn't compile at all
the array variable is null
You have access modifiers inside of a function
also yeah this won't compile
access modifiers? how to do it?
Is this the code you have in your IDE? If so, it should be underlined in red
No. I declare fields outside my methods tho. but i write the fields there just to see the fields of the variable.
How about you share the !code as it actually is
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so we can try to solve the problems you actually have
private GameObject[,] tilearray < this is declaring a new variable, so that doesn't match with what you're saying here.
instead of trying to figure out what is actual code and what is fluff
private Tilespawnner tiles;
private GameObject[,] tilearray;
void Awake()
{
tiles = FindObjectOfType<Tilespawnner>();
tilearray = tiles.spawnners;
}
public void OnDrag(PointerEventData eventData)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tile = tilearray[x, y];
if (y < maindict[GameObject.Find(dragged.ToString())][2])
{
tile.tag = "Opened";
}
}
}
}
``` Here
ok so yeah tilearray is null
How to make it not null then?
assign it to something not null
you did this:
tilearray = tiles.spawnners;
but tiles.spawnners was probably also null
so you just assigned it to null there
Probably a script execution order issue, since you're doing this in Awake
and there's no guarantee that tiles has itself been initialized yet.
I actually don't see any good reason you need the private GameObject[,] tilearray; variable at all
you can just do tiles.spawnners directly when you need it
so delete the tilearray variable completely and replace:
tile = tilearray[x, y];
with:
tile = tiles.spawnners[x, y];
How is this ambiguous? They are quite literally, the same parameter wtf?
Can you show the whole code? It might be seeing the same variable name but from different sources
also make sure you don't have a duplicate script
Because there's two things named HuntingChase.skillCD
Oh, yes, I renamed the freaking class intead of the reference by mistake
What a mess
I've got a question about vehicles. When designing the code for a vehicle that players enter and control, who is doing the moving? The player? Or the vehicle? Which object should be converting inputs into movement? If it matters, vehicles might sometimes have multiple players in them, and/or NPCs.
My hunch says the player is converting inputs into actions, but the actions are vehicle methods.
Your input should be separate from the thing that is being moved, all that you do is change the target transform/ rigidbody which the inputs control.
input -> target is set as player -> moves player around
player enters vehicle -> input target swaps to vehicle -> vehicle moves around
player exits vehicle -> input target swaps back to player
Having mupltiple players in them isn't going to affect that, just the first person in gets control of the vehicle
Got it. That makes sense and was along my lines of thinking. When you say "Input Target swaps to Vehicle", do you mean swapping to a different action map in the Input System?
Or do you mean that somehow there's a logical component that manages "what the player is controlling" - FirstPersonController or Vehicle
Best to use a different action map, it avoids the issue of needing to convert On Foot actions to what would make sense for that kind of vehicle. Plus you can make an action map for each class of vehicle, if they behave differently.
Like aircraft would have different controls from cars
Forgive the sloppy whiteboarding:
This is how I understand it to work, but I'm not certain.
So the InputSystem has various ActionMaps for different vehicles (right now I'm working on an emplacement that players can rotate with the mouse of thumbstick, and click to shoot)
My first person controller uses mappings from the "Player" Action Map. And my emplacement would use mappings from the "Emplacement" action map (above that's "Vehicle")
I sort of understood that there should be some "Player" object that sits between these two that literally defines the player themselves, whether they're controlling a FPS character, or a vehicle, that toggles between the "input target" of the player, and the "input target" of the vehicle.
Is that...remotely on-track?
You could do it a number of ways. Like when the player enters a vehicle you can just turn off the script(s) on them that are listening for input, and enable the one on the vehicle. As long as the player is attached to the vehicle somehow, either by parenting or using a position constrait and rotation constraint (I prefer constraints, less messy than parenting), then the vehicle will carry the player around.
when using a CC, does it matter if i disable the colliders of the player-object that the CC is attached to?
how can i make field in class where when i change it it also changes all memberwisecloned classes
the character controller is basically a capsule collider, so you don't need that at all
(what are you using it for anyways? you shouldn't have an RB with a CC)
I'm exploring different options of how I could move a character, starting of with CC, then going to RB
So, if I use a CC, I should delete the colliders of the objects child/parent to the CC
I didn't add the collider, just came with the capsule
CharacterController serves as a sort of ad-hoc collider on its own
You wouldn't have any other colliders on it if it has a CC
I see, thanks
This should be checking if a point of the NavMesh exists within 0.1 of the candidate point right?
I am not sure if I understood this method right
With a CC, what should I do to rotate the player? transform.Rotate or smthn like that?
Because the .Move() is pretty neat, but I can't seem to find any similar method for rotating
what do the docs say?
Not sure if you responded to me Carwash, but CC docs don't say (as far as I've seen ofc)
aye, just looked.. doesn't say.. because ye know, that wold be useful
The CC effectively ignores/has no concept of rotation so yeah just via the Transform
Note that you can't really rotate it except on the y axis
There is no concept of rotation with the CC, you have your velocity which you steer into a given direction (rotate the vector).
The CC is always upright
If you're referring to the visuals of the player, that also has nothing to do with the CC. You simply handle that however you want, such as lerping the forward direction of the model towards the velocity of the CC.
Yeah I find a lot of methods that I'm guessing can be used to rotate an object based on input. += new Quaternion. SetFromToRotation, SetLookRotation, RotateTowards, Slerp, Lerp, (all Quat.Euler ofc). Then also the Transform.Rotate. Do they all work? any I should avoid or is better?
Vector3.Lerp, Quaternion.Slerp (which I think I'm currently using for a simple CC)
Would that be a Quaternion.Euler.Slerp? or do you use the actual Quaternions?
transform.rotation is a Quaternion, yes
Because I don't think I will understand them good enough to use
I watched a 3b1b video about it and it looks so confusing (4d rotation?!?)
You don't need to actually know how Quaternions work, nobody really does.
Unity has built in functions for handling them for you.
And ways to convert simple Euler to Quaternions.
I wonder how they made those functions
did unity hire people that do know how quaternions work?
At no point will you ever need to care about the numbers. Just treat it as if it were class called something like RotationData and operate on it like you do other back box classes like colliders and rigidbodies
obviously
dark magic I tell you
uhh yeah so i recommended that, not as a learning tool, but as a window into what quaternions are, to hopefully convince yourself - "i don't need to understand this, i can treat it as a black box"
it samples nearest point on candidate if possible with 0.1 max dist ye
The idea is getting a random point but that is within the NavMesh, I am guessing that's right then?
you know the docs not only explain it better, but also has code sample that already do what you ask..https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMesh.SamplePosition.html
no worries nothing wrong in asking for clarification
Is the Quaternion.Slerp the same as the Vector3.Slerp? (if you convert the Quaternion into Quaternion.Euler? maybe)
In that they're both spherical linear interpolations, yes
It gets you a Quaternion that is some percent of the way between two others
Vector3.Slerp deals with direction vectors, not euler angle vectors.
So yes, but not if converting to eulers.
You can't use Slerp with Euler angle vectors
Well you can but it's not really going to give you the correct results
hm. So, I'm confused. Say that I want to use the Vector3.Slerp function to rotate my char based on input. How would I do that? Do I acess the objects rotation via transform and equal it to a Vector3?
This sounds so basic, I don't know why I can't connect the dots myself
Vector3.Slerp gets you a direction that is some percent of the way between two other direction vectors
if you do transform then something like transform.rotation = quaterion.slerp ( quaternion.euler( etc
but then to set rotation I'd still do playerTransform.Rotate(Vector)
you either have a function meant for what ur doing.. or you just use conversion methods in the process
So in the end its all just transform.Rotate?
transform.Roate rotates a value by the given degrees on each axis
no not .Rotate
ooooh, so there are two options then. 1) directly .Rotate 2) to change in the transform.rotation?
transform.rotation = quaterion.slerp ( currentRot , targetRot
I'll play around with that exact formulation, tyty
is the objects current rotation stored as a Quaternion? and not a Vector3?
always quaternion. if it was stored as Vector3 it would break and experience gimbal lock
but you can do .eulerAngles on any Transform or Quaternion
if u swap ur inspector to Debug. u can see the Extra W property 👀
hehe..not very useful.. but yea rotation is a quat
firs thing i always do when dealing with rotations 🤫
unless im using one of unity's nifty methods where i dont need to 💪
you would be a madman to do anything with quaternion floats heh
Quaternion helper methods are very nice, like Mathf. leave the heavy math to someone else lol
Mathf is the best thing since sliced bread 🍞
for example 📺 All these rotations are done w/ Mathf and MoveTowardsAngle
normally its the only thing i need.. but even if not it tends to get the ball rolling
Darhk ^ may be the only thing u need is ur input a degree's per second variable and Mathf.MoveTowardsAngle but dont know the specifics ofc
yo thats sick! WIll check out
hi! still working on my flappy birds. It works almost fine but when the bird dies it restarts from where it dies, without resetting all the pipes and bird position...
reload the scene?
I do but it's freezed since the game starts as freezed
thats desired tho right? u dont want the game to start until u press the button indicating ur ready to play right?
yep
i put the reload scene in the game over function
but It doesn't resets
SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex);
i should use this?
How are you reloading it?
w this
Show the !code where you call that
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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!
You'll need to show more context to get proper help
Okay, and are you using any additive scene loading or DDOL objects? Can you send a screenshot of your unity window before the restart happens?
you mean hierarchy?
The whole window would include the hierarchy
and also the console
and probably inspector
there are 4 of that and they are all referred to player.enabled
Just for future references, when you get an error during runtime, expect things to not work as expected (producing undefined behavior)
Then fix it
Errors mean the function ends immediately
so nothing after that line runs
The player variable doesn't contain any player...
The referenced variable player was likely null
yeah, but I can't drag my player in it
Seeing the error and stack from the console would be useful
I'm not sure what you're talking about. Player is a public field
That would indeed explain why it's saying the player variable doesn't contain a player
yeah but when i go to drag it into the flied I just can't do it
Are both objects currently in the scene
Maybe what you're dragging isn't a player or not something valid within the scene (vice versa). We'd need to see stuff to make better suggestions
I need to write something inside the bird script to make it mark as a player?
Show a screenshot of the inspector of the object you're trying to drag in to the player slot
You need to answer this #💻┃code-beginner message question and provide more detail
This does not have a Player component on it
So of course you cannot drag it into a slot that expects a Player component
Where's the "Player" component? 
ohhhhh I'm burned
I was seeing how some people did the script and they eventually called the birdcontroller "player"
thanks you everyone sorry if I bothered you with that stupid problem..
public BirdController player;```
I believe it works now if application.entermode wouldn't get stuck
Likely so. Zero errors would have the scene loading statement behave as expected (destroy and recreate the scene with it's default parameters)
Okay, so I know Move() should be FixedUpdate() but the camera jitters substantially more than if I also run it in Update(). Is this bad?
thanks you thanks you
Are you moving with rb physics? What about the camera?
Are there any other objects in the scene moving with rb physics?
I'm using a CC, the scene is a plane + 2 cubes that are stationary and I'm walking around + moving camera to test jitters
the camera is attached to the player with a child object
Anyway, are there any negatives with running the Move() code inside of normal Update()?
It depends what Move is actually doing
well basically its just the cc.Move() function
even if I code for input accumulation it doesn't improve the jitters
the difference is actually night and day
with the function in Update();
Once moving Move() to FixedUpdate();
If you decouple the camera from the player, does the player move appropriately?
i mean yes, but the point is the camera being jittery, and that (Im 99% sure) is caused by desync in player movement and camera movement
because of inputs being recorded frame-by-frame and then Updated with FixedUpdate() is not frame-by-bframe
With RB physics, you'd be able to move the player using interpolation and also move the camera in late update to avoid jittering issues. I'm unsure about CC.
am i doing something wrong here?
WWWForm form = new();
form.AddField("PhotonApplicationId", "--");
UnityWebRequest webRequest = UnityWebRequest.Post("https://---.playfabapi.com/Client/GetPhotonAuthenticationToken", form);
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("X-Authorization", ClientSessionTicket);
await webRequest.SendWebRequest();
this just gives a UnityWebRequest.Result.ProtocolError Debug.LogError("HTTPS Error: " + webRequest.error);
Assuming you aren't moving kinematically and whatnot, it'd be fine as long as you're operating with forces. If you're directly modifying position/velocity, you may get some strange behavior with collision detection.
i can share more info if needed
Entirely possible the networking channel knows more about Photon (i think)
am i doing the right thing tho? cause i dont see any SetRequestBody so ig i add it in WWWForm right?
I wish I could help you, but I've only dabblewd with Fish-net as multiplayer ;/
okok I solved, I swera last question, I don't understand why the game restarts as i press spacebar when I never wrote that in any script
Work backwards. When would the game restart? (likely when it thinks you've died)
its fine Darhk, thanks for atleast chatting lol, i went on and asked in the playfab server ig
So why would it think your bird has died?
I'm wrong, the gameover button disappear after 1 second because it reset the scene..
Using RB, should my Rotate() still be using Update() or no?
The character or the camera?
Here's a discussion recently about jittering camera and rb
#💻┃code-beginner message
What's the actual error?
HTTPS Error: HTTP/1.1 400 Bad Request
thats from my debug btw
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
Debug.LogError("Connection Error: " + webRequest.error);
return null;
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError("Error: " + webRequest.error);
return null;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError("HTTPS Error: " + webRequest.error);
return null;
case UnityWebRequest.Result.Success:
string json = webRequest.downloadHandler.text;
GetPhotonAuthenticationTokenRequest response = JsonUtility.FromJson<GetPhotonAuthenticationTokenRequest>(json);
return response;
}
i do know what it means i just dont know whats wrong in the code 😭
can a www form be used with json? 🤔
idk it worked on my other API calls
for other things, not for playfab
idk much about this, but is ---.playfabapi.com correct or just a placeholder you forgot to replace?
forgot to mention, i just used --- to blur out important information
thats where the title ID is
i would get a different type of error if the url would be incorrect
If the content should be json then you should encode json yourself
wdym by that
The docs mention that 400 is just a wrapper error. Perhaps you should check the contents of the response for actual details.
Reminder that using RB physics will have your objects simulating actual rb physics. You'll get cheap freebies (collision and trigger detection/behavior) but also have to fight whatever comes with actual rb physics that may be unwanted for video-game-physics/non-rb-physics (friction/sliding, high speed collision detection issues, etc)
Unfortunately, I'm not sure how to fix your original jittering camera issue with CC.
you set the content type header to json but give a www form which should actually be used with application/x-www-form-urlencoded (as the content type)
yeah but in this case, the response shouldnt be set tho right?
if you say that www form wouldnt work with the json response
am i dumb, why isnt this block falling when using RB?
response? you are making a request?
a post request, yeah
i dont know what this api wants but you need to give the correct content type header for what you send. If you say its json then send json...
man i dont know what to send i dont understand this api honestly
it says i should send this
string and string
also i checked the debug.log for error
right now just added more error debugs to show message
will try what u said in a minute
okay
you can use JsonUtility to serialize a class to json or use Newtonsoft JSON to serialize a Dictionary<string, string> to json
yeah thats what im doing
stop using a www form
It should unless you've set time scale to zero or gravity to zero etc
no I checked that
could you please help me change it cause i dont understand how to change it
start by learning what JSON is firstly... https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/JSON
oh my god i sent the app id and all 😭
i shouldnt rn since i didnt finish this yet 😭
if you sent your api key time to make a new one
the api key will be public anyways, people will always have it
photon itself said you dont have to protect it, to protect you need to add authentification to the app
ive been using json for such a long time but hell yeah lets start again xD
Is it on top of something else in the scene (an invisible collider/floor etc)
no, the same set up works in a clean project some it has to be a setting of sort
wonky shite
this?
Good point if its shipped in the client.
You want to create a json string then send that as the post request body 👍
ah, so create the json and then ship it as body, got it, but how do i ship the body? i cant find any method in UnityWebRequest
the main overloads take a string body... https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Networking.UnityWebRequest.Post.html
UnityWebRequest webRequest = UnityWebRequest.Post("https://---.playfabapi.com/Client/GetPhotonAuthenticationToken", "{ \"PhotonApplicationId\": -------- }", "application/json");
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("X-Authorization", ClientSessionTicket);
await webRequest.SendWebRequest();
So like this yeah?
cause it still gives the same error :/
Why are public variables bad? I've been working around them just because i've heard they're not good to use, but why?
i will fix it myself trust me
Because they can be changed by anything at any time without notice.
its just "bad" practice, by making it private you are not gonna secure your code, but just make it not changable by other of your scripts
Like a malcious client? or like dev error
The idea being other things shouldn't be allowed to touch them directly, rather than public fields it's preferable to have a public function that gets and sets that value or a property by doing
[field: SerializeField] public Type myVariable { get; private set; }
dev error, it's to help yourself (or other programmers)
in theory if i see a public variable its a sign that I should be allowed to touch that without fear of things breaking
which means that value either needs to be safe to mess with or protected from things messing with it
They inflate the situations and configurations you have to test/consider and it becomes very easy to overlook some when the code ages
gotcha, so it's just good practice
yeah, it doesnt matter at runtime or anything
i have my private variables, then public variables that get the private variables right now
{
get => moveSpeed;
}
see here
i fixed it, thanks a lot rob5300 if you see this message by any chance
Gotcha. Thank you much, that's a whole lot cleaner
[SerializeField] public float MoveSpeed { get; private set; } = 5;
you need the [field: SerializeField]
basicially Unity doesn't serialize properties but if it's a auto property and you tell unity to explicitly treat it like a field it works
[SerializeField] and [field: SerializeField] aren't the same thing?
the latter targets the backing field of the property iirc
basically the auto property has this getter variable and private variable built into one
you gotta tell unity to care about the private one
Gotcha gotcha
but yeah either autoproperties with differing protection accessors or explicit functions that deal with getting and setting are almost always preferable to just a public field
Mind that [field: SerializeField] is liable to data loss because IDEs do not (yet) support automatic rename-migrations of serialized data for those.
I have an action in a class A:
public Action OnCollide;
I assign a function to it from another class in an intermediary class:
A.OnCollide += B.SetCollisionMarker;
I call the action:
OnCollide?.Invoke();
and the function in class B is never called.
What did I do wrong?
that's not really enough context to know what you did incorrectly. share the actual code
Class with action:
public class PhysicsBody : MonoBehaviour
{
public Action OnCollide;
private void OnCollisionEnter(Collision collision)
{
Debug.Log("collide"); // this works
OnCollide?.Invoke();
}
}
function where action is assigned:
{
foreach(var body in PhysicsManager.instance.bodies)
{
GameObject trajObject = Instantiate(trajectoryBodyPrefab, this.transform);
PhysicsBody trajBody = trajObject.GetComponent<PhysicsBody>();
trajBody.mass = body.mass;
trajBody.velocity = body.velocity;
trajBody.rigidbody.position = body.rigidbody.position;
trajBody.transform.position = body.transform.position;
trajBody.name = $"trajBody_{body.name}";
GameObject trajLine = Instantiate(trajectoryLinePrefab, this.transform);
TrajectoryLine line = trajLine.GetComponent<TrajectoryLine>();
line.name = $"trajLine_{body.name}";
line.body = body;
line.simluatedPhysicsBody = trajObject.GetComponent<PhysicsBody>();
trajectoryLines.Add(line);
trajBody.OnCollide += line.SetCollisionMarker;
}
}```
class where desired function exists:
```public class TrajectoryLine : MonoBehaviour
{
public void SetCollisionMarker()
{
Debug.Log("SetMarker"); //does not work
}
}```
just printing "collide" is not useful at all, consider printing some more info, like what object is invoking the event. then you can do some more debugging to figure out why that object does not have anything subscribed to it
and also make sure you aren't ignoring/hiding any exceptions in the console
Gotcha. But I'm using the action and invoking it correctly?
minus whatever spaghetti is stopping it?
I would recommend using the event keyword here but otherwise yes
why event over action?
My guess is that the instances you're subscribing to are not the same as the ones that are colliding
It's not either or
You still need Action
event just means that only the class that owns it can invoke it
Or reassign it
public event Action OnCollide;
By adding the event keyword here we might even reveal the issue if it leads to a compile error somewhere.
I have no idea what this is referencing
depends what you did recently. Could just be editor bugging out, try a simple restart of unity first if keeps showing then dig deeper
Every time I run EnemyTurn() and one of the if requirements are met, that happens (and yes I am aware that this code is absolute dogshit)
https://paste.mod.gg/ellojlrrjsga/0
A tool for sharing your source code with the world!
would suggest not checking floats with ==
Ok I think it's an error with the order of execution but for whatever reason my player isn't physically jumping despite the line of code being called. I feel like I'm missing something obvious. Again the line says it executes but I'm not getting the jump itself.
https://hastebin.com/share/edikejujok.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is this ghetto?
rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z);
ghetto isn't a suitable word in that context
yeah, you're right
follow through with your logic line by line. First you set currentVelocity to be what rb.velocity is. Next you calculate the x and z values. Then you set the rb velocity to be the currentVelocity. Then you calculate the currentVelocity.y value.
Same thing happens next fixed update: you set the currentVelocity = rb.velocity. That old currentVelocity.y value is never used
sorry but could u elaborate
0.9999999999999999999999 != 1
Floating point inaccuracy means you should almost always either do Mathf.Approximately (if you expect that the two values are actually approximately close), or use a larger threshold like if (Math.Abs(a - b) < TOLERANCE)
but... I don't use floats in this script, only ints
Vector2.Distance(, that's a float.
_player.transform.position.x that's a float.
Oh shit ur right, thanks
I am spawning enemies only on server/host
player1 starts the game, clicks start host, set itself in a Manager as a reference being the host player and enemies start spawning, take the reference from the Manager, and start following this reference on update
I let this run for a minute and it's fine
but when player2 joins as a client, for some reason it throws an exception on player2 console that the script EnemyFollowPlayer has a null reference of target player to follow
even though the enemies are set to only set to spawn on the server
any idea what's going on? please note this suddenly starting happening today it was running fine before
We don't see your code but it's not like your code is making stuff up. Something is null and you are trying to access it. You may think it functions one way but you need to prove that to yourself through debugging.
Tbh if you aren't familiar with debugging null errors, you most definitely shouldn't be touching multiplayer yet.
And mostly multiplayer issues should be in #archived-networking or the unity multiplayer server
Hey yall, i have a problem I could not solve even with the help of chatgpt+ and countless debugging hours. The code in the pictures are all in different scripts, the problem I have is the third picture with the Debug.Log("Before...") and Debug.Log("After...").
For Example:
When newID gets a new id with the help of ItemInformation.Instance.GetNewItemID(), it works perfectly fine, the GameObjects kxInfo and cxInfo get the correct ID. If I have 3 gameobjects the instantiated objects (GameObject kxInfo = Instantiate(ItemInformation.Instance.kxInfoPrefab, ItemInformation.Instance.gameObject.transform);) look like this:
1000
1001
1002
And the logging looks like this:
Before:0
After:1000
Before:0
After:1001
Before:1001
After:1002
This makes absolutely no sense to me and if I look at the instantiated gameobjects then they have the following ids:
1000
1002
1000
which is even more confusing to me. Goal is to have the same ID as the instantiated kxInfo/cxInfo Objects.
I hope i could explain my problem somehow understandeable with my broke english
!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/
📃 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.
please share your code as specified above ^
real quick, what part are you confused about? what's happening, or why it's happening?
the logs and ids you've shown seem to be pretty self-consistent
they point to an issue, yes, but they point to the same issue
it seems pretty clear to me what's going on, but it'll be hard to confirm/explain without seeing how all the methods flow, so it would help if you could share more complete scripts to show that via the links above
shall I also record a video?
haven't shown where GetNewItemID() is called either
sure did first pic
and second
ah, missed it all the way up there right at the top of 2nd pic
do i put the code on this side and post the link?
basically, yes - make sure to save first though so we can see the code too
The code you showed has little context around the log statements so it's hard to know what you're logging and where you're logging it
there are logs in the 3rd image but it doesn't show where it's being called from
Not knowing which script everything is in hurts
A tool for sharing your source code with the world!
i know sorry i did not now that pasemod exists
you're good, we've all been there
how can I show yall my screen recording
ill setup a drive link to my screen recording if you want to look at it
so u understand the problem better if yall trust me that much
so seems like the second and third objects you place have the same name
so when you go to place them, you call shelves[currentShelfIndex].PlaceItemInShelf with those same-named gameobjects
then PlaceItemInShelf passes those to ItemGridItems.Instance.AddCorrespondingItem
then AddCorrespondingItem gives you gameObjects based on the name - and since in the second and third instance, they have the same name, you get the same prefab back
back in PlaceItemInShelf, that means you're getting the same gameobject twice - so you see the second object getting overwritten with the third ID
does that sound about right?
the other option is that maybe you accidentally set multiple of the "prefabs" in ItemGridItems to the same GO
Too much reliance on strings and object names
but if they're actually prefabs, well, you never call Instantiate on them, you just use them directly?
that seems like a much deeper issue
i know that I get the prefab, but thats why i try to set the ID here:
GameObject objToGive = ItemGridItems.Instance.AddCorrespondingItem(objToPlace);
objToGive.GetComponent<ShelfItemHandler>().ID = ID;
i know but thats one of my first projects and rewriting everything is not worth it
that doesn't really make sense
like how are those 2 statements related
are they actually prefabs? if so, you probably shouldn't be editing them, but editing instantiated versions
here i get the prefab
GameObject objToGive = ItemGridItems.Instance.AddCorrespondingItem(objToPlace);
and then I set the id of the objToGive
objToGive.GetComponent<ShelfItemHandler>().ID = ID;
which is then stored in the List<Gameobject> and that list is used to instantiate the items in a different script with a foreach.
AddCorrespondingItem(objToPlace) gives me the prefab you sav the code to that script
you shouldn't be modifying the template
yes but I modify the objToGive?
which is, apparently, a prefab
oh god damn wait a minute