#π»βcode-beginner
1 messages Β· Page 253 of 1
so what is the difference between quaternion.euler and transform.eulerAngles
On is a method. The other is a property.
No idea. Probably that one works and other doesnt)
XD
Do you know what a method is?
i keep forgetting things
istg i knew what it was 1 hour ago
i just forgot π
Void Euler(float x, float y, float z)
Go through the C# basics again then.
i think it was public void start and update
Quaternion.Euler() is a method that takes 3 args if I am correct. It may take more
or whatever void you create
maybe im tripping here
alright
So does the line I wrote work?)
yep
That's just examples. What is method actually?
Great. And it works like intended in playmode?
like i dont know the definition exactly
And how is different from a field/propetly?
havent tested
i have no clue of what a field or property is
That's the problem. You don't know what it is. You just know several examples that fit that category.
That's why you should go learn properly
yeah i have no clue how to explain it without sounding dumb xd
Then if it works I have many questions to people who Xed my first and initial message
ill try in a sec and tell you if you want
Now that I have it deleted can't name those smarties
im trying to think how to explain what a method was
Yeah, I would be happy to know that you got it done and it works
its like a void you create that you can either call from other place or just run in a loop if its update
thats my logic
Yeah, that is kinda correct if you ask me.
@teal viper
You can call it from other place if it's public or static though
From outside the class where it is
i dont know the fancy words (because as i said i learn them in spanish and maybe the traduction fucks it up a bit) but thats like what a method is in my mind
for example a coroutine would also be a method
it doesnt need to start with void
i think
public void YourMethod()
private void YourMethod()
ill trans
ffancy words
its not like they exist in this exact context but since i have talked a lot with dlich i mean other times where i dont understand words its due to not knowing that they are a word i know
for example reference or "referencia " in spanish
i didnt learn it with the word reference nor referencia
im sure it will be fine
i just understood that it existed and didnt give a fancy name to it
in my mind they are more like concepts associated to functionalitys than associated to words like method reference value type etc etc
@visual hedge btw it works
i just need to add the force to move them i think
Knowing english on a certain level helped me a lot with unity. Most guides I watched are in english.
Or give the gameObject a vector to move...
i dont watch them in english for the same reason, they usually use more (as i like the calling them) "fancy" words
Great) I wonder why it wouldn't, just wanted to know)
Γ actually do it like that
i use the rigidbody for their velocity
idk if thats a mess since most people use rigidBodys for physics based movement tho
Sounds good to me. But I honestly have not so much knowledge in sending projectiles at desired direction
tyler do you want to see how it works ? xD
it does rotate it but ig i messed up how much they rotate and what the direction is
I have one question: is it just me, or some people in this channel are so pros, that they can't give proper assistance to newbies? I've met that many times here and also with my friend who is actually unity employee ))
it depends
the help i usually get is aimed towards newbies
and they try to explain all inside the whole thing
What you call "fancy words" are actually important concepts that help understand how things work.
for example caesar navarone aethenosity or dlich
Yeeah show it π I won't be able to help though. Maybe someone else will
how can i record my screen again?
i think i can take it from here tbh
alt + windows + g?
maybe they actually point towards the direction but since they all go up atm it gives the optical illusion of not working
I use some app made for screenshots and videocapture for that)
They should spawn at 180 degrees to the previous projectile?
each time its zRotation + 60
so in 6 loops its 360 and it has completed a whole "rotation"
Ohh yeah, now it makes sense π
i think the rotation works its just the direction at which i launch it that doesnt makes sense
well usually people will just answer a concept and guide what to do. No one really wants to explain the absolute basics to every new person that comes and gives up on unity in 1 week because they dont know what an int is. There is a certain point where most of us just stop answering a person, and tell them to go learn the basics of c# first.
Well you shall run them at that white pointer direction
So use the transform.position of that white pointer as a direction
nono i want them to just go around it
not towards the white pointer
Yeah, understand. But that's not what I meant
makes total sense tbh
if you want ill dm it to you once i am finished and it works like intended
I was like 2 days in and friend said: yeeeah, for this you want to use (pseudocode further:) singleton and bunch of static methods and well maybe some non- euclydian quantum physics bullshit.
BHAHAHAHAHAHAHA
i feel you
but nah people on here has a lot of patience really
im gratefull for it
atleast the people who i have treated with
While some will shoot lambda expressions at newbies
π€·ββοΈ id consider everything except the exaggerated quantum physics to be c# basics
While all newbie needs is to mske their int FruitNumber = 1; public
KEWK
That's what you learn if you go through a structured course.
We expect you to know to do that already.
In beginners channel?
Yes.
this is game dev you are talking about. The people who refuse to learn the absolute basics first will face WAY more stress than people who took maybe a week of their entire life to do the basics first
sorry I had to go over to my teacher about my project and then had to go to my next class, I'm not sure what you mean by this.
for instance I have a movement vector2(x,z) and which is at (0,1) so forward, this is under a gravity direction of (0,-1,0) so down.
then gravity is set to (1,0,0) which would be to the right.
and what I think you're saying is that I need to find the difference in rotation between (0,-1,0) and (1,0,0) and multiply the (0,1) vector by the result?
Beginner is meant for people going through that learning process. And if they encounter difficulties during that time,they can turn to this channel for help. But there's not much point in helping them if they are just writing random code and don't try to learn the basics orderly.
I guess that's the reason why all newbie guides almost ALWAYS declare all the variables as public π€£
It's fine to make variables public it first. It's way more important to understand concepts like OOP, classes instances, value, reference types, etc..
I might expect from someone in general to use private serialized fields. But it's totally fine to use public fields as a beginner.
Yeah. For sure
Beginner courses are not meant to teach you good code practices. They are meant to teach you to write at least working code. And understand it.
Oops... what is oop?
Good practices come after that.
Object oriented programming...
Oh, right
Till last week I had no idea what that is by tbe way
Then someone said that unity is oop and it made petfect sense then))
By the way... not a beginner topic, but... visual programming seems much more complicated than coding by hands (and brains) is?
From vids I saw... having hundreds of "boxes" with strings going everywhere looks bulky and complex to me
It's not hard. Just takes getting used to it and a bit of learning(like everything). It's confusing for someone that's used to writing normal code, but that's about it.
A ye, one last thing: out of interest went to old chat with that friend. 2 months later I perfectly understand what he suggested back then. It even appears that 2 months later I came to what he suggested by myself somehow.
I guess I asked the question 2 months too early
lot of how unity works kinda ruins a lot of that idea of private and public access, so it's best not to try to be a perfectionist because you really cant and this is due to the fact that you can't use constructors with monobehaviors
there's some methods like events and subscribing to methods to help lessen the fact that you can't bind via constructor, but even then it's a very loose implementation.
Ow, yeah. Constructors is something I have to learn also now. Soon I want to get into automatically generated skill descriptions based on what the SO is set up to. And if I get it right, I need to learn to use a string constructor
so if you need your item's Use() methods to be used by your controller only, but you can't construct your controller with your inventory's reference to keep it private, then the best course of action is just make your Use() behaviour public, or bind an event after through some assignment method.
Wow i face this issue a lot. What i do, usually converting fields to a property and setting it's getter setter to "public get" and "private set". Similiar like u said but it is just cant happen always... Sometimes the things those needs to be private becoming a public :d
serializing on the inspector does help with binding and keeping accessors private, but sometimes you do need to instantiate independent objects which aren't prefab'd together where it causes complications
and then you'd do assignment usually after the constructor has been called if needed, and this is usually through some assignment method
meaning that you're more forced into an dependency injection (DI) approach, which is actually more ideal for something like game dev since reusing objects is always better than cleaning them up and instantiating another copy.
im trying to make an endless runner. the rigidbody on the road causes the player/ball to bounce a lot, so I made a bandaid fix to stop that, but wanna go back and fix the root of the problem so I can make obstacles that causes the player to fall through gaps if they miss a jump. that said, in this video, the left and right work perfectly fine, but as soon as I try to use the jump button, it acts out. how can I fix this? the player sphere has a rigid body, and the prefab empty containing the road has a rigid body.
Not on topic but... am I the only anxious one because of ball having cube collider and cube rigidbody?)
why does the road have a rigidbody. Is this some endless runner tech
yea, its an endless runner game. i have it as a rigidbody so it collides with the trigger off screen to delete it and procedurally keep going
thats what the tutorial told me to do
if it doesnt have rigidbody, it doesnt get destroyed
I think they imply that you have to use velocity for rigidbody
or something liek that
this is what happens behind the scenes in the game
What exactly is the issue? I don't see anything wrong in the video. Is it that the jump goes sideways? Should it not jump like that? How should it jump? These things are not entirely clear unless you explain them.
I don't know too much endless runners so I don't know the best way to move ground if the player is the one who is stationary, but usually when you use rigidbodies you are using rigidbodies' movement methods over directly changing the transform position.
always best to keep player stationary and move obstacles/roads towards player
this way you dont get a huge amount of position and get weird jank
there are 2 inherent issues. 1 is that without an invisible collider, this happens, but i would like to not have to worry about that so I can get creative with obstacles and have the player fall. the second is that jump that you saw. when you press the button, it just goes wonky, like flying off the screen and falling and what not. not to mention it gives more height/force than id like on the lift up
btw this looks like the one of those fake games from ads π
yea I know lol. I have an interactive game design class starting next week where I thought wed be making an endless runner, so I wanted to start toying around with the idea. now I realize we dont have to, but i still wanna mess with this lol
I don't understand what "this happens" means. Please explain it in words.
As for the jumping, share the code relevant to jumping.
the video. without the collider with no rigid body keeping the ball smooth/stable, the ball jumps and bounces every time it hits the floor, and thats not intended
have you tried using sphere collider and sphere rigidbody? π
the ball has a sphere collider?
oh, okay, my bad
I would try using rb.moveposition
two rigidbodies acting on each other seems like something you want to stick to rb only methods
The ball bouncing from the floor sounds like a normal behaviour for a default rigidbody. Do you want it not to behave like a real physical objects?
and whats rb.moveposition
at the moment, Id like it to only jump when the player wants to jump
where do i put rigidbody.MoveToPosition(), what do I put in the brackets, and what does it do?
idk, ask them π
the IPointerHandlers are for clicking on your object, is that what you want to do?
seems odd
for a jump script
I see everything is working for you and instead of helping with jump issue we got to discussing why the road moves like it moves damn
share code related to jumping please
I mean... I'm not an expert but I would do that thru simple if GetKeyDown.Keycode
the road is moving now?
so it's fixed? π
not really. i have an invisible collider with no rigidbody working as a bandaid, but i dont want it there so the player has a risk of falling. also, the jump is still messed up
falling due to intended reasons, not this hot mess
one thought is I could just perma-bandaid this and when I get around to adding obstacles, just mold colliders around it
again, you're using transform positional logic when you should be using rigidbody methods in fixedupdate
idk what that means
I also dont get how that would fix my problem. would the platforms still be the thing moving? can you please explain why I should be using rigidbody methods in fixedupdate over what I am currently doing
because rigidbody uses physics which happens in a fixed time step
not only that, but movement is evaluated differently as there's a lot more to it than simply changing the position (interpolation, prediction, ect)
Currently, aside from moving it in update sometimes, you let the rb move freely. Imagine a real life ball filled with air dropped from one meter height. Of course it would bounce.
If you want a completely controlled movement, you'll need to set it's velocity manually every frame.
im guessing that isnt advised cus its computationally expensive
What is?
No, it's totally fine. You're just changing a value that unity physics works with.
how would I do this then?
id like the player to be grounded unless they choose to jump, or they fall through an obstacle. how would I go about doing that?
with your velocity suggestion, I mean
Actually, instead of setting the velocity, maybe applying force and using a non bouncy material would be better.
There are many ways to go about it.
yeah, there's like 5 ways to move rb, but you've chosen the one way to not move it ;p
i just did what the tutorial told me to do
its so weird, it behaves like I would want it to at first, then just kabloom
I lowered the force variable from 10 to 5 to see what happens
thats what this video shows
so what, I would replace Player.transform.Translate(0, ForceTime.deltaTime, 0); with RigidBody.Move(0, ForceTime.deltaTime, 0); ? im not really following the syntax. im more familiar with unreal blueprints syntax and my coding is rusty lol
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
The docs can be pretty helpful and will sometimes write the code for you
@dark kettle just a random idea: in rigidbody try to lock some axis
I did that with both the player and the road
actually, sometimes the docs won't throw you the exact right code as seen in AddForce there, but you don't want to be taking input in fixedupdate either
the velocity code does it right though
Share the tutorial
That movement looks like the rb is either colliding with something from the left or a force is applied to it sideways suddenly. The code that you shared so far, shouldn't be doing that imho.
Btw, what's with that crazy mass? I wouldn't be surprised if it's contributing to the issue.
regardless of the mass, if you're changing transform position directly, physics will be trying to fight it because it doesn't respect velocity
Still, that shouldn't cause such a specific behavior
well, it wouldnt leave the ground regardless
I think I know what the issue is
Hey friends! Let's learn how to generate infinite levels and platforms in Unity with Procedural Generation! This is a follow-up to a video I made about Subway Surfer, and I thought this would be a good overview on how procedural generation works.
πΎ Join the Discord! https://discord.gg/MYAujpE4xG
π«Ά Access Code Files and Projects! [patreon.com/...
This Video shows that Movement using Button in Unity3D. This video contains Left, Right and Jump Movement Using Button
Image Link : https://www.pngwing.com/en/free-png-vvvlx
#unity#unity3D#movement
physics is like you belong on the ground, but translating it upwards is like saying no u
Ok I see, so you tried putting several not so great tutorials together...
Can you take a screenshot of your ball inspector with constraints on the rb expanded?
@visual hedge
i tried to follow a different tutorial on jumping and accidentally gave my jump button a directional pull that i cant get rid of. lollll
my last 10 hours of being alive in a 20 second clip
Hmm... Okay, maybe that's not it.
yay
oh I see, even though I deleted code, my jump button had a rigidbody on it
i did some beautifull work for figuring out how to impulse it
Nice, now make a whole bullet hell system
caesaaaaarrr!
omg I made this work, not sure if this is the best way to do it but now I just need to rotate based on the camera's forward I think 
Vector3 crossProd = Vector3.Cross(Physics.gravity.normalized, GetGravityDirection().normalized);
float angle = Vector3.Angle(Physics.gravity.normalized, GetGravityDirection().normalized);
Quaternion rot = Quaternion.AngleAxis(angle, crossProd);
Vector3 transMove = rot * absMove;
InputVector = transMove.normalized * magnitude;
``` does this make sense?
iΒ΄ve been coding nonstop for the las 10 hours (except a mini break for having breakfast) and all for this, even tho its not much im still so proud
the joy im feeling right now is something from other reality
(imma stop yapping now, srry but im so excited)
im back to square one, my jump button no longer has gravity, and my ball acts weird with its jump, and im using a collision box to bandaid the rigidbody issue
here are the other constraints, for reference. I noticed when I was working on the first tutorial that the roads were bumping into each other and these constraints, plus adjusting the number in the code fixed it. heres a screenshot of the code as it is right now, for reference
lowering the number from -57 as the tutorial says to do (then later lowers it herself) to -10 fixed the collision issue, along with the constraints
I suggest getting your sphere to jump in place using addforce first
also, pushing left/right against the wall leads to it bouncing off the wall
how do I do that
try some physics material to prevent it from bouncing if that's intended behaviour
could really be a few things honestly because you've two rigidbodies acting on each other
if I'd attempted this, I'd probably wouldn't use rigidbodies and just do most of the logic directly through transform updates
this way you have more control of the behaviour and it seems like that's a requirement for you
how could I go about doing this? that tutorial I shared earlier used rigidbodies because the platforms wouldnt move otherwise, and I guess it worked perfectly fine for her. I could see if she has a video going over movement on her channel
probably the hardest problem with that would be smoothly interpolating ramps but not impossible
what does that do
look up kinematic character controllers, that's probably what you would want to use
ah, I guess you would also add some velocity to ramps in that case too
looks like she doesnt have a movement tutorial for the endless runner. I may look at a different procedural generation video and kinda do a partial reset on this project, since im not really far into it anyways
her video doesnt explain anything for the player
she slaps on a rigidbody and moves it incorrectly
yea i was looking to see if she does a player tutorial and she didnt
in her videos
so im gonna find someone else to learn about procedural generation from
theres probably a bunch of tutorials on this stuff so yeah, look around
this guy hasnt posted in ages, but has a 3 video series on the subject. im running version 2020.3 anyways, so should work for me
Is that desired behaviour?)
his procedural generation looks cooler anyways lol. I am thankful I followed the first tutorial though, because it got my toes wet in the world of procedural generation, which Ive never messed with in any game engine before
Learning quickly, well done π
unity does have an endless runner template you should consider digging into
just to see how they're doing it
What is the purpouse of small white triangle?
player
but i dont control him since discord only allows 25 mb and didnt want to overexted the video
And the thing that shoots is enemy?
yes
and small cubes that appear on top also are enemies
Okay, so Galaga you have π
what is galaga?
Oldschool 8bit space game with spaceship shooting
That's what I am working on π
Assumingly the only game genre that the market is not oversaturated with. Or maybe I'm just not so aware
Or maybe noone plays turn-based games π€£
Hello, I have not been able to find a good solution to very simple thing π¦ please help
- 3d game with only x and z axis. y axiz = 0 always
- Mobile Touch game
- Player gameobject moves to location where touched
- if Box gameobject is in the way of Player movement, Player goes around box
- if Player clicks on Box gameobject, Player stands next to Box with a maxdistance 0.6f ( any edge )
I can not make 4. and 5. work
I have tried
A. AI agent - can not make 5 work
B. Vector3.MoveTowards - can not make 4 work
C. use targetPosition.normalized and write algorithm for every delta movement ( tough algo)
please suggest, it seems a simple task, but I am not able to catch it
How to make my camera can't look all way down.
https://gdl.space/ixajokikov.cpp - The Camera Script Attach to Character
I want my player can't look all the way down to make its doesn't break the game. Please help.
is there a way to rotate the orbits from the freelook cinemachine camera?
I tried all the binding modes but they don't seem to work. maybe I'm not using them properly
how do i make it not readonly
i tried changing the folder attribute but it keeps reverting back
Hi, got a Cache related question. Got a FSM on my player, each state will need to get reference of components to do things.
Is it better to cache my components at their first access in a collection and then my states will access this collection to get refs, or each state must cache it's needed components at it's start?
looks extremely good if you are developing alone
I do it alone. The only things I haven't made myself are 3d models (textures) and particle effects. 3d models are taken from the depths of the internet π
how do you fix a _unity_self null error?
AFTER 6 HOURS I HAVE DONE IT!!!
heres the code that i needed π
targetrotation = new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(targetrotation), 5 * Time.deltaTime);
parent.transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(targetrotation), 5 * Time.deltaTime);```
this code it prob breaking like 70 laws of c# but idc. it has given me the behavior i want.
show the stack trace
yes it does. that's the stack trace at the bottom
and it is from editor code, so unless you have been writing editor code or you have an asset that has editor code then you can clear it and move on
π
how do i get a relative direction of an object? wasent it gameObject.transform.right? somereason that doesnt work...
it's transform.forward is the direction it is facing
yeah but i want the right relative to what direction its looking. so its right not the worlds right
if you get what i mean
then look at the docs for the Transform class and see which property you should be using https://docs.unity3d.com/ScriptReference/Transform.html
Hello, I want to ask about music, here is the question
Is it faster using FindGameObjectWithTag or searching for the instance of the script?
This is the code with FindGameObjectWithTag:
https://paste.ofcode.org/NyPudz4LGbNzSpmQmMqkXq
This is the code with instance:
https://paste.ofcode.org/TQRHBzMhWgQMTDAa3q8FJE
Thank you!
alright cool thanks
It will always be faster if you cache an instance of something. Or just make it a singleton so you can call it directly.
also if you dont have a gameobject with tag audio then NRE or it returns a gameobject without this component and NRE again
Is it okay if every music and sfx I want to Play and Stop are using instance? I'm not aware of how singleton works.
NRE?
what is line 86
A singleston is just a static class, which means you can only have one instance of it. This is ideal for things like managers, and will let you call code directly from it without having to first create a reference.
AudioManager.Instance.PlayJumpSound();
Aahh yes, that's what I do, I'm doing instance
the list not null how about the elements?
then whatever in that index of the list may be null, or its Base property is null. or its text property is null.
ok
Instance isn't a thing, you can call it whatever you want really. But keep doing it that way then, rather than searching for the AudioManager at runtime.
This is what I do:
AudioManager.instance.gameOverMusic.Play();
AudioManager.instance.levelMusic.Stop();
the gameOverMusic and levelMusic is an AudioSource.
Sure, that works
Okay, now I know this way is better than FindGameObjectWithTag. But is this singleton way of playing music and sfx is good in terms of performance?
bro what
1 operation vs # of elements on the scene to search through to find the audio manager
ima noob man π
if you think that is anywhere close to valid code, you should go through the beginner courses pinned in this channel
how do i make it valid
You don't need to micro optimize this. Yes it's fine.
start by learning wtf you are doing instead of just taking random guesses at what you think the code should look like. you're going to take longer to fix your issues than it will take to learn if you have no idea what you are doing
Okay, thanks
Ok ok ok, I dont need to worry about this then, thank you!
Hey everyone im having some issues here with the List Variable. https://paste.ofcode.org/ixgXps6H58ruk5pW6smJN4 when I call RemoveChest, it always leaves 1 left in the list. How do I combat this? (I think it has something to do with list starting at 0 maybe?)
so whenener I spawn another ChestSlotPrefab it always doubles the item in the list because it wont be deleted for some reason.
&& instead of & ?
yo
im watching that tutorial as well
are you missing the script thingy in the inspector
moveText != null && moves != null I guess was the first mistake where mistake was & instead of &&.
second one, list is declared, you don't want to see if it's not not null, but if it has any elements in it, so you have to check element count
also I think that if you are watching a tutorial... you do it terribly wrong since I am pretty sure Brackeys wasn't writing it that way
@hidden sleet you writing a poem there? π Sorry... could not resist to @ you )
so you answer me and then write the whole poem anew after π
basically yeah. Got an issue with interfaces and inheritance so I'm trying to formulate it into a question that isn't too bloated
this one will work a tiny bit better if you put 3rd string before the last curly bracket
For this inventory system of mine I've got it set up so that said inventory will hold a list of InventoryItems. ```cs
public class InventorySO : ScriptableObject
{
[SerializeField]
private List<InventoryItem> inventoryContainer;
This inventoryItem class then holds a scriptable object representing an item, as well as a quantity.
```cs
public class InventoryItem
{
public int quantity;
public ItemSO item;
When the Ui is clicked, it will pass the index of the slot that was clicked, which matches the inventory's indexes, and I'd like to be able to spawn the item into the world from here. However each type of item has different rules for when and how it spawns.
private void HandleItemSpawnRequest(int itemIndex)
{
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
inventoryItem.Spawn() // Wont work
}```
I figured I could try an interface, ```cs
public interface ISpawnable
{
public void Spawn();
}```
And put it into the item that can be spawned ```cs
public class RawItemSO : ItemSO, ISpawnable
{
public string[] labels;
public void Spawn()
{
//Spawn into the world
}
}``` But I believe my understanding was off, as I can't call the spawn method since the inventoryItem is just an itemSo, which doesn't have the method on it.
So given that I will have different classes extend this raw item, each with different spawn logic, what would I have to change up here so that I can just call that spawn method in my HandleSpawnRequest method?
haa! I knew it will be a poem!
indeed X/
even a novel
tried to cut out unecessary stuff but in essence it's just that I don't know how I'd go from a list that holds the superclass, to then calling the method located within the subclasses
may I suggest one thing? That you use Kryzarel's inventory system?
I initially thought that if I have ItemSO as the type, then anything that extends that could fit and I'd be able to just call that method from the interface, but I'm not sure about that now
Sounds like ItemSO should be an abstract class that implements the ISpawnable interface.
If every kind of ItemSO can be spawned, it should implement the interface.
But if there's no specific definition, you can implement it abstractly.
Derived classes will then have to provide an implementation of the method.
I cant' really help you sadly, but when you spawn item... you better spawn an unique item and not copy of your initial item... because that will cause some troubles I am afraid
yeah in this case everything will be spawnable in one way or another
So if I make ItemSO abstract, and put a RawItemSO in that inventory slot, would doing inventoryItem.item.Spawn work?
right
ItemSO is not ISpawnable, so it doesn't have to have a Spawn method.
so if I go and make the itemSO abstract, and put the interface in there, would subclasses of that also need to implement the interface or just override what the base ItemSO does?
They will need to override the abstract Spawn method.
They only need to inherit from ItemSO.
Right then, so I've got ```cs
[CreateAssetMenu]
public abstract class ItemSO : ScriptableObject, ISpawnable
{
public bool isStackable;
public int Id;
public string Name;
public abstract void Spawn();
} with that spawn method as abstract. Raw item so overrides that.cs
[CreateAssetMenu]
public class RawItemSO : ItemSO
{
public string[] labels;
public override void Spawn()
{
Debug.Log("Spawned");
}
}Then in the controller I just need to call spawncs
private void HandleItemSpawnRequest(int itemIndex)
{
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
inventoryItem.item.Spawn();
}```
Correct.
fantastic!
that's going to make my life so much easier
Good good
will do some extra research
There just seems to be so many ways to extend, override and manipulate classes and whatnot that figuring out the correct way to do what I want feels rather tough
but this seems to solve that
constructing it in the SO is fine
This is roughly how I've done items in the past
if Item is a plain c# class you can use that with a constructor
The scriptable object references a prefab
constructing what?
The item as new Item(ItemSO)
well I'll see if I can apply this in other places, had a mess before where I had multiple inventories of different types, with spawn logic all over the place. basicallt rewriting it all now
If you ever find yourself doing this, you probably need polymorphism:
if (thing is Foo fooThing)
fooThing.Work();
if (thing is Bar barThing)
barThing.Work();
ironically, one place I wound up having to do that was...an inventory system
i wanted to keep separate lists of each kind of item
yeah I ended up with this exact same situation with my last inventory
It feels very easy to wind up with this kind of code in an inventory system
I could keep one big inventory list and then filter it as needed, but then I'd be inspecting the exact types of each object to do that
I guess each class could have a Type property that returns an enum
but then you'd still need to downcast to access functionality that only some items have
Parent parent = new Child();
Child downcasted = (Child) parent;
in case you haven't seen that term before
Child child = new Child();
Parent upcasted = (Parent) child;
upcasting goes to a parent type; downcasting goes to a child type
upcasting always works; downcasting can fail if you have the wrong type at runtime
Like, i had this for an inventory where the contents are just simple items. cs public class Inventory : ScriptableObject, ISerializationCallbackReceiver { public ItemDatabase database; public List<InventoryItemSlot> invContainer = new List<InventoryItemSlot>(); public string inventoryType;
Then a separate one for structures... ```cs
public class StructuresInventory : ScriptableObject
{
public List<InventoryStructureSlot> invContainer = new List<InventoryStructureSlot>();
One for raw stuff... ```cs
public class RawItemInventory : ScriptableObject, ISerializationCallbackReceiver
{
public List<NewInventoryItemSlot> invContainer = new List<NewInventoryItemSlot>();
public string inventoryType = "RawMaterial";
public GameObject spawnPrefab;
And one for processed items.... An absolute mess cs public class NewProcessedItemInventory : ScriptableObject, ISerializationCallbackReceiver { public ItemDatabase database; public List<NewDatabaseInvItemSlot> invContainer = new List<NewDatabaseInvItemSlot>(); public string inventoryType = "ProcessedMaterial";
the compile-time type of parent is Parent; the run-time type of the actual object stored in the variable is Child
Then I had all these trying to display the items for each
so I'm trying one where I can just have a generic item and hopefully it'll figure the rest out
I have yet to implement an inventory system that I really like π«
this is only for a small uni project but it's already giving me headaches
everytime I try to be witty I end up with generics and then hate myself for it
I just dislike casting
I'm making a game in which the number of characters could go up to the hundreds during runtime. Would it be feasible to have a script attached to each of them which controls their pathfinding? They also have different "jobs". What's a better way of doing this?
Although thinking about it now, Spawn is currently in the item class itself. If I intend for this to just instantiate an object and attach this item as a component, should that spawn logic be in the item at all?
you need to distinguish the item definition from the actual item
The item definition should be able to instantiate an actual item for you when needed
(that's how I've done it)
so my inventory isn't a huge pile of deactivated game objects floating below the player
not too sure how I'd go about that
Use scriptables
you'd probably have a motor script on each entity, but you could look into unity's dots and the job system for larger amount of units
Use scriptable objects for your items
I joined 2 seconds ago lol
I was saying, it can work both ways. You can construct it in the item, or instantiate the item in the SO and do the logic there.
Wait
go about what in particular?
Your inventory is a scriptable?
you need to be specific, especially when you have 10 different item classes floating around (:
What I would do is have a inventory component that is basically a dictionary of itemScriptableObjects
what's a motor script
your pathfinding logic
Not too sure what you really mean by splitting the definition from the item.
Currently I've got all the possible items set up as scriptable objects, and the slots just reference those ones. Is that somewhat similar?
okay
Do you have tangible GameObjects that represent your items in the world?
Or do they only exist in your inventory?
I figure you do, given the Spawn method.
Yes, but they don't always exist. Essentially, when you start the items are scattered on the floor. You pick them up, and go into this ethereal inventory. But in some scenes you can click them and I'd want them to spawn as a prefab in the world to then use for some other purpose
Personally, I like to have a ItemConstructor singleton that spawns the items into the scene, but mostly more network related instead of independent item instantiating.
Okay, so ItemSO is your item's definition. It's how you refer to the item in the abstract.
"I have 500 sheets of metal" means you have an InventoryItem with a count of 500 and the "metal sheet" ItemSO
The actual metal sheet prefab is the real item.
If you have the "metal sheet" ItemSO, you should be able to instantiate the "metal sheet" prefab.
yup, got the possible ones set up here.
thus, its ItemSO (which will actually be a ProcessedItemSO or something) needs a reference to the metal sheet prefab.
How do you guys find the object that throws a null reference? The console shows me which line in which script it is, but it doesn't tell me which object in my scene is missing the reference. It's really hard to figure out when you have many objects, hundreds, that could be the culprit.
Would that prefab end up in that scriptable object to be assigned in the editor?
See if clicking on the error in the console highlights anything in the Hierarchy.
Log entries can include a unity object as context
It could be prefabs too which contain the nulls
You'll need to do this while the game is running.
If the error is coming out of a prefab (rather than an instance of the prefab!), clicking the error may highlight something in the Project window
Thanks, @swift crag and @timber tide , it's probably in the prefab.
Drag the console window out separately from the project window and try clicking the error.
If that doesn't work, then consider just doing something like Debug.Log(this.name, this); right before the line that errors
The second argument to Debug.Log is the context.
Oh, ok.
Right, so if I go and put that prefab in this scriptable object, that spawn method could just instantiate it from that directly
Correct.
gotcha
It could even assign itself to the newly spawned item, so that the item can get things like its name from the RawItemSO
public class ActualItem : MonoBehaviour {
public ItemSO definition;
}
public class RawItemSO : ItemSO {
[SerializeField] ActualItem prefab;
public override void Spawn() {
var spawned = Instantiate(prefab);
spawned.definition = this;
}
}
Oh, you got different prefabs for different items eh
something like this
Cause once it's spawned, I want to put the item on the object, since some physics interactions later will do something based on what type the object is
This will be useful if you reuse the same prefab for many things
ActualItem can ask ItemSO for its name
If you have one class for each kind of actual item, then I'd consider doing something like this
Yeah yeah I think I have something similar already
although quantity shouldn't be there
public abstract class ActualItem : MonoBehaviour {
public abstract ItemSO Definition { get; }
public string Name => ItemSO.ItemName;
}
public class RawItem : ActualItem {
public RawItemSO rawItemSO;
public override ItemSO Definition => rawItemSO;
}
The concrete RawItem class actually holds on to a RawItemSO
the Definition property lets it return its RawItemSO as an ItemSO.
Thus, ActualItem can access it and read stuff from it.
Alternatively, you could do something more like this
Yeah, this is one problem I dislike but I guess that's just oop, but the return type is still the same in the child.
Was wondering actually, I know about the concept of getters and setters as a way to control how private variables are retrieved and set, but with the {get;} notation, does that just essentially allow you to do definition.Get?
public abstract class ActualItem : MonoBehaviour {
private ItemSO itemSO;
public string Name => ItemSO.ItemName;
public virtual void Setup(ItemSO itemSO) => this.itemSO = itemSO;
}
public class RawItem : ActualItem {
private RawItemSO rawItemSO;
public bool Smeltable => rawItemSO.Smeltable;
public override void Setup(RawItemSO rawItemSO) {
base.Setup(rawItemSO);
this.rawItemSO = rawItemSO;
}
}
Which is why I'm always drawn into doing something like Item<RawItemSO>
This is a bootleg constructor, really
You call RawItem.Setup(), and it calls ActualItem.Setup() to pass the definition along
That was an abstract property declaration.
public abstract int GiveMeANumber { get; }
You must implement a property that has a public getter
how is that different to just leaving it public and doing an =
Properties look like fields, but they actually call methods.
When you access GiveMeANumber, it calls a method that returns an int
notably, since there's no set accessor here, you can't try to set the property
public string Name => ItemSO.ItemName;
So, if you have an ActualItem, you can do this:
Debug.Log(item.Name);
it will ask its ItemSO for its own Name field or property
so you don't have to say GiveMeANumber.get, but rather whenever you try to get it like you would a normal public variable it runs through that method instead
Correct.
right
Did some stuff in java and I kept making specific methods for getting and setting, so is that essentially just a shortcut
So weird, yesterday I got 4 errors and a trigger wasn't working, today I open the project and run it - no errors and trigger works fine. How weird!
private float myField;
public float ReadOnlyForYou
{
get => myField;
private set => myField = value;
}
this property can only be set by its own class
I use a lot of get-only properties in my code.
can I express this line here Tesst.trueDamage = Mathf.Round(Tesst.trueDamage * unit.Stats.critDamage);
as:
Mathf.Round(Tesst.trueDamage *= unit.Stats.critDamage);?
No. The assignment has already happened before Mathf.Round is run.
Tesst.trueDamage *= unit.Stats.critDamage returns the value that got assigned to Tesst.trueDamage
Mathf.Round rounds it, and then the result is discarded
so better to leave it this way, right? Tesst.trueDamage = Mathf.Round(Tesst.trueDamage * unit.Stats.critDamage);
got it. I'll experiment with that later then
gotta get some lunch now, hopefully all goes well but I may be back later if more issues arise
Yeah, the return is what you want from the method, but if you did want to make your own method with that behaviour you'd use Ref parameter.
vs should really warn you on discarding the returns
note that ref wouldn't be usable here, since there's no variable -- just the value returned by the *= opreator
because you can totally ignore TryGet methods
I meant, wrap the round method and use your own ref parameter
ah, hmm. I guess you'd have to make it a pointer then
can I access/edit these two values via code ?
i think i can
i think its these two
that are X and Y poses respectively
but i dont see the third parameter
oh ye =/
you'd want the children property, which is an array of https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Animations.ChildMotion.html
I've never manipulated those before
but one thing to note for sure
A copy of the list of the blend tree child motions.
Try getting the children property and storing it into a variable
Modify that variable, then store it back into children
Otherwise, you'll just be modifying a copy that gets immediately thrown out
do you have a question?
Is there something that needs fixing?
index is out range?
Doesn't seem like a problem
you have 4 move texts
and less than 4 moves
that's expected in pokemon
im not sure what these mean
i mean how to fix it
ik what the problem is now
Is something actually broken?
ye bcz it hasnt learnt it yet
so it shoudl just show - instead
but for some reason
all of them are -
what does the inspector have to do with the list of Moves that is passed into this function?
this doesn't look like anything relevant to the cdoe above
Where does the list of moves come from
This may be a dumb question:
no it doesn't
then it comes form the other one
It comes from the Pokemon
same class name
is it
playerUnit.Pokemon.Moves
ok
guys a little help on #archived-code-general
don't crosspost
shall i start debuggine in the poekmon class
You should definitely start debugging this moves list Β―_(γ)_/Β―
and figure out why it's not populated properly
!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.
ok
use paste sites
but none of the code matters all that much atm
you need to look at the data
I have this screen on unity for a cockpit im using for a game in creating, there is also an image of it in game. I want to actually animate this to show current health and enemy positions, but not sure of a way to do it. Is there any way i can edit this to make the movement, or find a way to replicate this?
Again im aware this is a dumb question
but just incase i can
if all you have is that image, it will be hard
you would need like a "base" image without the populated text and values in it
then you could animate the stuff inside it
but - if you just have that specific image it will be annoying. You need to photosho out the "cutrrent" values on it
can i dm u
Make a thread
So start by sharing your code in a bin site
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
public class Pokemon
{
public PokemonBase Base { get; set; }
public int Level { get; set; }
public int HP { get; set; }
public List<Move> Moves { get; set; }
public Pokemon(PokemonBase pBase, int pLevel)
{
Base = pBase;
Level = pLevel;
HP = MaxHp;
// Generate Moves
Moves = new List<Move>();
foreach (var move in Base.LearnableMoves)
{
if (move.Level <= Level)
Moves.Add(new Move(move.Base));
if (Moves.Count >= 4)
break;
}
}
π 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.
Literally just read the bot message. You're wasting your own time, considering how short on time you said you are.
does anyone know why this instantiates 2 objects instead of 1cs GameObject output = Instantiate(new GameObject());
Because you're creating a new object, then cloning it
because new GameObject creates a new object in the scene. then you pass that to Instantiate which creates a clone of it
makes sense
public class Pokemon
{
public PokemonBase Base { get; set; }
public int Level { get; set; }
public int HP { get; set; }
public List<Move> Moves { get; set; }
public Pokemon(PokemonBase pBase, int pLevel)
{
Base = pBase;
Level = pLevel;
HP = MaxHp;
// Generate Moves
Moves = new List<Move>();
foreach (var move in Base.LearnableMoves)
{
if (move.Level <= Level)
Moves.Add(new Move(move.Base));
if (Moves.Count >= 4)
break;
}
}
Nintendo lawsuit in the making
jokes aside whats the problem
this is the problem
ik what the problem is
ive located it
but dont know how to fix
public List<Move> Moves { get; set; } = new List<Move>();``` Moves was null so there was no list to write data to
Where do you set Base.LearnableMoves
nvm
im stupid
im confused as to why you arent using inheritance
It does seem l ike a sort of ghetto inheritance
Okay where do you set learnableMoves
What is the best way of setting a rotation. There are many ways, so I wanted to hear ur opinion on the best.
Hello, so I have an object that damages the Player. In the future I want to add more than 1 trap objects, should I only make one script that damage the player or make one script for each object? Because I kinda want to diferentiate the nature of each traps.
What is the best solution for this? Thank you!
in the pokemon base?
is that what u emant
Yes. Where do you set that list
What is in the list
ok
Make a script for a specific purpose. If that purpose is "Deals X damage when the player steps on it" then that can pretty easily be one script with an inspector variable
Whether that's dealing 5 piercing for a spike or 30 fire damage for a puddle of lava, doesn't matter, it's the same basic concept
ill remove the stats
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Pokemon", menuName = "Pokemon/Create new Pokemon")]
public class PokemonBase : ScriptableObject
{
[SerializeField] string name;
[TextArea]
[SerializeField] string description;
[SerializeField] Sprite frontSprite;
[SerializeField] Sprite backSprite;
[SerializeField] PokemonType type1;
[SerializeField] PokemonType type2;
// Base Stats
[SerializeField] int maxHp;
[SerializeField] int attack;
[SerializeField] int defense;
[SerializeField] int spAttack;
[SerializeField] int spDefense;
[SerializeField] int speed;
[SerializeField] List<LearnableMove> learnableMoves;
public string Name
{
get { return name; }
}
public string Description
{
get { return description; }
}
public Sprite FrontSprite
{
get { return frontSprite; }
}
public Sprite BackSprite
{
get { return backSprite; }
}
public PokemonType Type1
{
get { return type1; }
}
public PokemonType Type2
{
get { return type2; }
}
public List<LearnableMove> LearnableMoves
{
get { return learnableMoves; }
}
}
[System.Serializable]
public class LearnableMove
{
[SerializeField] MoveBase moveBase;
[SerializeField] int level;
public int Level { get; internal set; }
public MoveBase Base { get; internal set; }
}
One script for each object cuz it encourages & prioritizes creativity rather than reusable code
So we dont need to make each script for each trap, instead for a specific purpose but we diferentiate it by variables? Ok, is there any problem for the performance though or is it okay?
Is there any problem with the performance or optimization if I do this, or this is just the same with reusable code?
Performance wise there is absolutely no difference between one script and a different script that does the same thing
Do all ultility methods have to be in the script that inherits monobehaviour? Or can i have a separate script just for utilities?
And stop worrying about performance until you actually profile it
reusable code would probably be less performant
Okay, thank you
Ok, thanks
Depends on what you mean by utility
Now I know what I should do
Incorrect.
can i dm soemone
It literally does not matter where the code is it gets run one line at a time like always. The same content embedded in a function multiple times versus a function of its own literally makes no difference
so i can contact them later when there free
i mean less performant as in consuming more ram
So where do you set learnableMoves
Again, incorrect. It's literally identical. An instance of a script is an instance of a script. If they do the same thing there is literally zero difference between it being a different instance of the same script or a different script
Btw unless youre creating a game where theres going to be thousands of traps loaded in simultaneously you shouldn't need to worry about performance
Naahh, it's just a simple 2D pixel rogue-like game
i was thinking of it by thinking that some of the inherited class might just go unused but i get what you're saying
public Pokemon(PokemonBase pBase, int pLevel)
{
Base = pBase;
Level = pLevel;
HP = MaxHp;
// Generate Moves
Moves = new List<Move>();
foreach (var move in Base.LearnableMoves)
{
if (move.Level <= Level)
Moves.Add(new Move(move.Base));
if (Moves.Count >= 4)
break;
}
}
also premature optimization is the worst thing you can do
You only need to derive from MonoBehaviour if you want to define a new kind of component. If you aren't planning to attach this class to a game object, then there's no point.
there may be many traps, but not simultaneously pop up
Alright, I wont think about optimization again, it's a later problem
Still waiting to see where you actually populate the original list
Okay, show it
A script that houses physics calculations
Maybe be a bit more specific like explaining the dependencies.
Okay, so, now that we have the information let's follow the chain backwards from the error. Your first two moves in the list are throwing an error, the other two are throwing a warning because there's only two in the list. That would make sense since this list has two elements in it, so there's likely a problem with this list. Since the if statement checks if the move is null or the move's base is null, we can now say that one of two things is happening. Either:
A) The moves inside the list are becoming null, either by being set to that or being destroyed, or
B) The move's base property is or becomes null
Try logging moves[i] and moves[i].base instead of just saying "MoveText or Moves at index i is null"
Find out which case it is
Again, depends on which utilities you want. There are many things that are statically accessible from the Physics class, and others that depend on a UnityObject
well, they are just physics calcualtions for a car that i wouldnt want to be near the runner
unrelated math that doesnt actually effect components
the result of the methods are used
It seems like you can easily do this in a static class. I'd say just try and if anything says it needs a reference then move that to a monobehaviour
Do you need to remember data between function calls?
Or is this just a pile of formulas?
If you're just doing basic arithmetic without any Unity dependency, there's little reason for you to couple the utility class. Without any specifics, I'll just assume it doesn't need to inherit mono behaviour
[CreateAssetMenu(fileName = "New Trap Object", menuName = "Trap")]
public class TrapScriptableObject : ScriptableObject
{
[field: SerializeField] public Damage { get; private set; }
[field: SerializeField] public DamageInterval { get; private set; }
[field: SerializeField] public List<Effect> EffectApplications { get; private set; }
[field: SerializeField] public Sprite sprite { get; private set; }
}
public class Trap : Monobehaviour
{
TrapScriptableObject SO;
//runtime assignment
public AssignTrap(TrapScriptableObject SO)
{
this.SO = SO;
//set sprite and stuff
}
//editor assignment
public OnValidate()
{
//set sprite and stuff
}
void OnCollisionEnter(Collision collision)
{
//Apply SO.Damage every SO.DamageInterval to player
}
}```
Some ideas. You can also just use multiple prefabs if you want to just have specific gameobjects with set sprite and collider radius ect without sticking that info into the SO. This idea shines more when you have more than a couple of traps with different degrees of damage, otherwise making multiple prefabs and setting values directly in the editor works fine.
If there aren't instances of data, you'll not need an instance.
kk thanks
I've got these SOs on my inventory now, but I'd like to view each item as a drop down. Is there something I'm missing to do so? ```cs
[CreateAssetMenu]
public class RawItemSO : ItemSO
{
public string[] labels;
public override void Spawn()
{
Debug.Log("Spawned raw");
}
}```
[CreateAssetMenu]
public class StructureSO : ItemSO
{
public StructureSerialised structure;
public override void Spawn()
{
Debug.Log("Spawned structure");
}
}```
Is it because the inventory slot is just a base ItemSO type?```cs
public class InventoryItem
{
public int quantity;
public ItemSO item;
public InventoryItem(ItemSO Item, int quantity)
{
this.item = Item;
this.quantity = quantity;
}
public void ChangeQuantity(int newQuantity)
{
quantity = newQuantity;
}
}```
You mean you want to see more derived items in the drop down?
Yeah
Im pretty sure you can only do that with structs or a custom GUI script
As it is, yeah it'll show you everything that's derived from ItemSO
RenderTextureToRawImage(obj, newFeature.transform.Find("FeatureIcon").GetComponent < RawImage > (), renderCamera, renderTexture);
private void RenderTextureToRawImage(GameObject objPrefab, RawImage rawImage, Camera renderCamera, RenderTexture renderTexture)
{
GameObject obj = Instantiate(objPrefab);
obj.transform.position = renderCamera.transform.position + renderCamera.transform.forward * 2 f;
obj.transform.LookAt(renderCamera.transform);
obj.layer = LayerMask.NameToLayer("UiItems");
foreach(Transform child in obj.transform)
{
child.gameObject.layer = LayerMask.NameToLayer("UiItems");
}
renderCamera.Render();
Texture2D texture = new(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
RenderTexture.active = null;
DestroyImmediate(obj);
rawImage.texture = texture;
}
private(Camera, RenderTexture) CreateComponents()
{
RenderTexture renderTexture = new(256, 256, 24);
GameObject cameraObject = new("RenderCamera");
Camera renderCamera = cameraObject.AddComponent < Camera > ();
renderCamera.targetTexture = renderTexture;
renderCamera.enabled = false;
renderCamera.clearFlags = CameraClearFlags.SolidColor;
renderCamera.backgroundColor = new Color(0, 0, 0, 0);
renderCamera.cullingMask = 1 << LayerMask.NameToLayer("UiItems");
return (renderCamera, renderTexture);
}
why isn't it rendering the children of the obj?
right. That's a shame
Yeah, maybe naughty attributes can help you out, but as it is you've no constraints on the class so it'll always show what's insertable
Hello, can you explain me what does the currentVelocity parameter in Vector2.SmoothDamp do?
Add spacing to separate code, i can barely read this
What do you mean by viewing the item as a drop down list btw?
The issue is Discord's lack of syntax highlighting, not the code
https://dbrizov.github.io/na-docs/
Some useful attributes, but don't believe there's type support. I know Odin has something for it.
So I could potentially press an arrow on the side of Item and it displays everything about that item, since each is a different type
pseudocode:
int totalCount = PassiveSkills.Count + ActiveSkills.Count;
if one of those lists has 0 elements, will it throw an error?
im pretty sure naughty attributes only does special stuff if its passed by value like a struct or primitive
It would error if the lists do not exist
Otherwise no
this better?
yes
As is, you'll only get quantity and the reference SO as you've likely only got a list of InventoryItem. The fill data for the scriptable object instance would be on the asset.
so even if both have 0 elements, int totalCount will be 0, right?
WOWOWOWOWOW I'm not in the league of Scriptable Object yet, but I do get some ideas from making multiple prefab, thank you so much!
0 elements will give a count of 0 yes
thank you
Glad to help
What if all the fill data for the different items is unique?
So like, these processed items are one from a pool, but each structure will be different
What do you mean? The field you've got there is simply a reference to the SO asset.
post this in #archived-code-general you'll probably be able to get better help from there
stupid noob question, what would be else for this one:
if (someInt >= 0)
//blah blah
else
// blah blah
else would be like someInt < 0 or someInt <= 0?
Or I better use else if?
someInt < 0
else occurs whenever the if condition is not true
So, if the condition someInt >= 0 is not true, it runs else
Due to literally the definition of a boolean, a number can only be >= 0 or not
oh, yeah, silly me. So if it's = 0 or > 0, so else would be left only with <. PErfect, thank you. Brainfarts are such a brainfarts
Consider learning C# before delving into Unity. Learning both can be very tricky, especially considering Unity has a ton of practices that are going to make it very different and complex.
it ws a brainfart, sorry π
I am pretty confident in that topic just had some strange brainfart really π
What would you say is the best way to rotate just on one axis. there are multiple options like dealing with eulars or quaternions, etc. what is the optimal option rotating by a certain degree?
It seems then the issue I've got then is that my inventoryItem class takes an SO only, but in my case I might actually need it to be a custom class that isn't an SO. ```cs
public class InventorySO : ScriptableObject
{
[SerializeField]
private List<InventoryItem> inventoryContainer;
```cs
public class InventoryItem
{
public int quantity;
public ItemSO item;
If I want to keep the same code for the InventorySO class, but just have inventoryItem use a different type, say
public class InventoryItemStructure
{
public int quantity;
public Structure structure;
What could I potentially do to avoid having to duplicate and rewrite my whole inventory?
Quaternion.AngleAxis
so would i then add that quaternion to my transform quaternion?
well, you never add Quaternions and what you do with the result depends on what you are trying to achieve
Well, I am just trying to rotate a gameobject
i havne tused unity inawhile so im trying to remember this stuff do u multiply them?
A great aid to memory is the unity docs
which i have been going through
you have not even said what kind of rotation you want
I am guessing what you want is to change one of the axis of the eulerAngles, then copy that to quaternions and apply that
hi, could someone please give me an idea on how to make a sprite follow the mouse? (2D game)
x axis forward rotation
yeah, but i always would get this lock where it would rotate to a point and then lock
but is it going to be setting a rotation, or rotating an existing rotation
What do yo mean by lock?
he means gimbal lock
oh no he said the g word
Learn how to convert the mouse position on the screen to a real position in the game world in Unity
p.s. if you're using Unity's new Input System: instead of Input.mousePosition, type Mouse.current.position.ReadValue();
00:00 Intro
00:36 Get the mouse's screen position
01:50 Screen to World Point
05:30 Screen Point to Ray
09:10 Using a Layer ...
ty
rotating
an existing rotation
Could consider a more abstract type that has quantity, then make one derive with ItemSO and one with Structure
That's description is one of the less descriptive I have seen in my entire life. You talk like my mom
Literally just did that ;)
Remembered the discussion with Fen and I believe that'll do the job
although there's still more to do before I can test it
then you multiply
But I have this at the moment ```cs
public abstract class InventoryItem
{
public int quantity;
public abstract void ChangeQuantity(int newQuantity);
}```
public class InventoryPlainItem : InventoryItem
{
public ItemSO item;
public override void ChangeQuantity(int newQuantity)
{
quantity = newQuantity;
}
}
public class InventoryStructureItem : InventoryItem
{
public StructureSerialised structureSerialised;
public override void ChangeQuantity(int newQuantity)
{
}
}``` Which I assume will work
how do i fix this?
somewhere in your code #endregion is expected
figure out where #startregion is and what you're trying to collapse
However I'm trying to rewrite this section now. It's very messy, and is just supposed to convert an inputted item into another, but currently the output items are stored in this dictionary. Is there a better solution than this? ```cs
public class CraftingManager : MonoBehaviour
{
//Handles turning one object into another and holds the process to perform
public InventoryManager inventoryManager;
public RawItemInventory rawInventory;
public NewProcessedItemInventory processedInventory;
public List<SOItem> outputItems = new List<SOItem>();
public Dictionary<CraftMethod, SOItem> craftToItem = new Dictionary<CraftMethod, SOItem>();
public static CraftMethod craftMethod;
// Start is called before the first frame update
void Start()
{
rawInventory = inventoryManager.getRawInventory();
processedInventory = inventoryManager.getProcessedInventory();
craftToItem.Add(CraftMethod.RodCraft, outputItems[1]);
craftToItem.Add(CraftMethod.CuboidCraft, outputItems[0]);
craftToItem.Add(CraftMethod.PlateCraft, outputItems[2]);
}
public void ProcessInput(GameObject inputObject)
{
if (inputObject.CompareTag("RawMaterial"))
{
switch (craftMethod)
{
case CraftMethod.RodCraft:
processedInventory.AddStackableItem(craftToItem[CraftMethod.RodCraft], 1);
rawInventory.RemoveRawItem(inputObject.GetComponent<ItemController>().item);
Destroy(inputObject);
break;
case CraftMethod.CuboidCraft:
processedInventory.AddStackableItem(craftToItem[CraftMethod.CuboidCraft], 1);
rawInventory.RemoveRawItem(inputObject.GetComponent<ItemController>().item);
Destroy(inputObject);
break;
case CraftMethod.PlateCraft:
processedInventory.AddStackableItem(craftToItem[CraftMethod.PlateCraft], 1);
rawInventory.RemoveRawItem(inputObject.GetComponent<ItemController>().item);
Destroy(inputObject);
break;
default:
Destroy(inputObject);
break;
}
}
}
}```
is there a way to make these code blocks that we type expandable so it doesn't take up so much space. I feel like I blot out most of chat when I send something
All of this seem that would work better if you pass the value you want to modify the quantity for instead of the raw new value
i know where they are, and even when i remove the #region and #endregion i still have the error with the last }
Post large !code blocks using any of the provided links, save (the site should have a button up top for that) then post the link on discord.
π 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.
share your entire script -- without removing the #directives
kk ty
its to big but is the part where the #region starts enough?
need 2x end regions probably
You have two #region directives and only one #endregion directive
They are unbalanced.
ah i see, thanks
https://gdl.space/iyenuyuvin.cs I guess I am fine π
Anyone need any help? Ping me if you need anything
for (int i = 0; i < Tesst.endTargetList.Count; i++)
{
for (int j = 0; j < Tesst.strikeCount; j++)
{
ui.animator.Play("Attack");
ui.audioSource.Play();
yield return new WaitForSeconds(0.7f);
if (Tesst.canCrit && Random.Range(0, 100) <= unit.Stats.curCRIT)
{
isCritical = true;
Tesst.TrueDamage = Mathf.Round(Tesst.TrueDamage * unit.Stats.critDamage);
}
//stop striking the target if it's already dead
if (Tesst.endTargetList[i].currentState != TurnState.DEAD)
Tesst.endTargetList[i].TakeDamage(this, Tesst.TrueDamage, Tesst.isDodgeable, isCritical, Tesst.ignoreDefense, Tesst.targetStat, Tesst.isHeal, Tesst.applyStatusEffects);
yield return new WaitForSeconds(0.7f);
}
}
I need to implement the passive skill that would add +1 strikeCount while doing attacks.
So in the code above, where do I fire the passive skill code?
My thoughts were: Checking for any passive skill that is related to exactly between those: for (int i = 0; i < Tesst.endTargetList.Count; i++) { for (int j = 0; j < Tesst.strikeCount; j++) { and then then running their effects. right?
oh, yeah, btw, that Tesst was successful, so I better rename that struct π
Been looking into some potential solutions to this, would a strategy pattern help to make this less messy?
with instantiate how could i make more effects appear instead of just one
Instantiate more than one
like but how
Call Instantiate more than once
would that work for making a pen?
I have no idea what that means in relation to the previous question
nvm
what i meant was would it work if the mouse was being held down?
sure, why not
so how could i use it in a script if u dont mind
If you want to have a sort of drawing thing it's probably better to use a single line renderer and add points as you move the mouse anyway rather than instantiating anything
i would rather it instantiate atm
Just realised that after making these classes abstract, my inventory has broken. ```cs
public abstract class InventoryItem
{
public int quantity;
public abstract void ChangeQuantity(int newQuantity);
}
```cs
public class InventoryPlainItem : InventoryItem
{
public ItemSO item;
public InventoryPlainItem(ItemSO item)
{
this.item = item;
}
public override void ChangeQuantity(int newQuantity)
{
quantity = newQuantity;
}
public void SetItem(ItemSO item)
{
this.item = item;
}
}
more specifically, this line doesn't work anymore since the InventoryItem is abstract now. From this, how can I then add a new item
private List<InventoryItem> inventoryContainer;
inventoryContainer.Add(new InventoryItem(item, quantity));
Cause I want this to work for any kind of inventory item type, what would I need to change to adhere to this abstract setup?
cells[x, y].walkable = colliders.Length == 0 || new Func<bool>(() =>
{
foreach (var collider in colliders)
if (collider.gameObject.layer == LayerMask.NameToLayer("Level"))
return false;
return true;
}).Invoke();``` how bad of a practice is inlining functions like this
but how could i do if it if it was instantiate?
you don't need to construct a new Func<bool>
you can just write () => true or whatever
and it's pretty reasonable to do this when you only use that exact code once
If you use it many times, consider extracting it into a method
Abstract classes cannot be instatiated
if i dont construct a new Func<bool> then it doesn't compile
can u make a pen with instantiate?
You're instantiating an abstract, I think you mean go put a new plain Item there
Call instantiate multiple times
you need to invoke the anonymous method
(() => true)()
kinda funny looking
oh wait, that's wrong
Only thing is, if I put a plain item there then I can't also use the structure item I made earlier
unless I am misunderstanding
but would i do like but if i did it one after another it would create same clones and not fix it
ah, you aren't allowed to do that at all! go figure; I didn't realize that
Or you change the list to hold the plain item or you make it not an abstract class
Besides
Can't do that, I need it to be able to hold both
I guess that it is weird to use an anonymous function here.
You usually use an anonymous function when you want to pass it to someone else
is item an ItemSO? then just construct a new InventoryPlainItem
I'm not sure what specifically you're trying to do but if you plan on creating a bunch of things with Instantiate the solution is to call Instantiate once per thing you want to make. Whatever you do with them is up to you
why not just !colliders.All(c => c.gameObject.Layer != LayerMask.NameToLayer("Level"))
Otherwise, you have a design problem here. You don't know what kind of inventory item you even need to create.
You can also have an interface called IitemDefinition and have the SetItem, NameItem methods in there
And have a single item baseclass
probably a better way of doing it
you can pass them around as thebase abstract type, but you need an idea what the more derived type is for when you need to call those polymorphic methods. (at least on construction of the item)
i had no idea that function existed
Why do you set the quantity in the item class itself?
yeah the one going into that constructor is an ItemSO. But if I make that add a plain inventory item, how am I going to also add the Structure items later on?
it's part of Linq
gotcha
does anyone know how i can fix this?\
You can't add a double to a float
they either both need to be doubles or both need to be floats
(Float)amount
cant down cast from double to float, no?
Oh
not that you should anyway
The real question is why use doubles at all
cookie clicker :)
All of unity's internals use floats, you should use floats when dealing with numbers
You're gonna need a specific data structure for numbers that big. Doubles don't give you more numbers, just more precise numbers
Sometimg Mathf functions return doubles
im following a tutorial and he didnt get any errors
yeah true, that sounds like a fun project to add to my backlog of projects
You dont even get more precision by mixing the 2. Your precision is as precise as your weakest link, which is the float.
Show the tutorial
like what
Or require, either of those
So, still wrapping my head around this, but if I have these ```cs
public abstract class ItemComponent : MonoBehaviour
{
public int quantity;
public void DestroyItem()
{
Destroy(gameObject);
}
}
```cs
public class ProcessedItemComponent : ItemComponent
{
public ProcessedItemSO item;
}
And here I want to look at the component of the object, get that SO and remove it from the inventory,
private void ProcessInput(ItemComponent itemComponent)
{
craftingMethod.CraftItem();
rawInventoryController.inventoryData.AddItem(new ProcessedItemSO(), 1);
rawInventoryController.inventoryData.RemoveItem(itemComponent //WANT TO GET THE ITEM HERE);
``` Would I need some kind of abstract method for GetItem in that abstract itemComponent class?
like what
Mathf is literally named for the fact that it deals exclusively with floats
https://www.youtube.com/watch?v=A5f_uuL11Xg he starts with this at 5:51
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Make cookie clicker with this quick Unity tutorial. We'll even set it up so that it's SUPER easy for you to add your own upg...
I'm not on my PC rn but for some functions it asks for doubles
you missed the part where the property is also a double
Show in your code where you define CurrentSamuelPerSecond
Feel free to find one and link it to me
https://docs.unity3d.com/ScriptReference/Mathf.html
Are you sure you're not thinking of just Math? Because I've yet to see one
Idk, might be that I mistaken math for mathf. But I swear on my alive mom that mathematical function had double as parameters
I checked for you. None of the functions take or return a double
that would 100% be from the Math class which is, notably, not from Unity
"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: 148
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-3-14
oh

@hidden sleet so what are you doing with your inventory right now?
It seems to me that you're making it unnecessarily complicated
You would benefit a bit from having your items not actually be components. You would only really need this in the case of having a dropped item which you may pickup to your inventory, which I would use a different prefab which has a reference to the item SO that it is.
In summary, I've got an inventory script with a container. There are three types of items that can exist in an inventory. An inventory can only have one type, so there are three in total. I wanted, if possible, to only have one inventory script and design it so that it works the same no matter what kind of item is in it. But the issue I have now is that by doing so with abstract classes, I can't get the information I need.
In this case that is basically what's happening. In this scenario, you click on an item from one inventory, it spawns in the world, falls onto a crafter type object before turning into a different item that is put in another inventory
each inventory is a different SO asset, but I wanted them to have the same script contents as to now have as much duplicate code
{
StartCoroutine(CameraShake("GravitySlam"));
while(true)
{
if(gameObject.transform.position.y >= 13.4)
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x, 13.5f, gameObject.transform.position.z);
break;
}
if(onBotWall == true)
{
Debug.Log("working0");
gameObject.transform.Translate(gameObject.transform.up * Time.deltaTime * 30);
}
if (onTopWall == true)
{
Debug.Log("working1");
gameObject.transform.Translate(-gameObject.transform.up * Time.deltaTime * 30);
}
yield return new WaitForSeconds(0.00001f);
}
if(onBotWall == true)
{
onBotWall = false;
onTopWall = true;
}
else if (onTopWall == true)
{
onBotWall = true;
onTopWall = false;
}
}``` I dont understand why the first time this coroutine is called working0 gets printed like normal but then the if with working 1 on the second time its called doesnt get printed even tho onTopWall is true
But now I can't do this for instance ```cs
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
inventoryItem.item.Spawn();
Because now it uses abstract classes, I don't know how to retrieve the item in order to spawn it and it's prefab
Yes still in that case, the actual Item in your inventory still does not need to be a gameobject. You can still do it I guess but itll be more annoying. I would have a prefab specifically for items which are dropped, since you dont interact with them the same way you do if its in the inventory.
And im not entirely sure what your question is asking, but you are presumably removing a specific item, which you might wanna get by index or search through your collection of items for. This is stored in some array/list right?
My suggestion
Have a baseItemclass
This contains the icon and name
Then have derived classes for the specific item types
Then have an inventory class with a dictionary that contains one item type (alternatively have a list of dictionaries, this wall you'll basically have 3 inventories)
This way you can expand the item typed by deriving then again and adding more fields
No gameobjects involved
A list of dictionaries, god no
Just spitting out stuff
Or make a value pair class
Who cares
It's basically the same
The prefab would just be one prefab, for every single item. You swap out the model and whatever else you want, all it needs to do is carry a reference to what Item SO it is
That's called a library 
That's what I'm doing at the moment. I've got an asset for each possible item type with a prefab attached, and any of my inventory items that reference an SO will therefore have this. Got the whole thing here anyways to make it clearer. https://hastebin.com/share/xuyetufadi.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Why is your actual inventory a scriptable?
just found it useful to do. Maintains data between scenes, didn't see anything wrong with it
The actual inventory should be a monobehaviour
Unless someone more knowledge than me thinks otherwise
How come my vscode doesn't have IntelliSense like this guys video does
!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
β’ Other/None
π€ where are you seeing that his inventory is a SO? I see the items but the last script is a mono
I think for the time being if I was able to have a method in this abstract class that let me get the item, override that in the ones above, and return the correct type, that might fix the errors I've got
SO does not save data between scenes, it may reset randomly if the references are lost. It works differently in a build vs editor
I've already set it up the same way they have it setup
then you should have intellisense. if not you missed something or you need to regenerate project files
Public class InventorySO : scrobj
Contains a list of inventoryitem
I was thinking if I could do something like this, that might fix it. But I've got no clue what the return type should be if it will end up returning either a SerialisedStructure or an ItemSO
public abstract class InventoryItem
{
public int quantity;
public abstract void ChangeQuantity(int newQuantity);
public abstract ### getItem();
}```
could someone please explain too me on how to instantiate multiple objects if the mouse is held down
do you know how to check if the mouse is held down?
not much to it, just keep instantiating
kinda
do you know how to instantiate an object?
thats waht the last person said
ye
I regenerated my project files, and followed the steps again and I still don't have intellisense
so then what are you confused about?
so combine GetMouseButton with Instantiate
its just idk how to do it multiple times
like im making a pen so like drawing
but its only making little dots rn
you can always return the type as the base then do type comparison
if(Input.GetMouseButton(0)) Instantiate(etc..
is that srsly all??
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
pretty much
@hidden sleet this describes it
Tldr
Use static keywords for non Monobehaviour object and Gameobjects
Use DontdestroyOnLoad for components and Gameobjects
Use Xml or json files to save data on the computer
https://stackoverflow.com/questions/32306704/how-to-pass-data-and-references-between-scenes-in-unity
then check the vs code console to see if there are any relevant errors. if you still cannot get it figured out, then consider switching to a real IDE like Visual Studio which is much less likely to mess up the setup
the idea is try to keep as much behaviour polymorphic, but when it comes needing to know the type, you need to start doing comparison or manage a way to keep track of the type
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
drawing = true;
if(drawing == true)
{
Instantiate(effect, pen.transform.position, Quaternion.identity);
}
}
if(Input.GetMouseButtonUp(0))
{
drawing = false;
}
}
i had that
do i not need that then?
What would that base return type be for that approach?
isnt that just the same (what i wrote)
This would be the abstract class of the Item. But honestly I've gotten lost on what the real issue is due to unrelated stuff. If you want to make a thread I can reply better.
nope
You can create a thread in this channel
it does the same
GetMouseButton and GetMouseButtonDown are pretty different
it does not. you need to re-read your own logic
you can hold GetMouseButtonDown as long as you want, its not gonna do anything after it ran that 1 frame
GetButton is every frame
GetButtonDown is called 1 frame when pressed
so wouldnt i be better using getbutton?
you can return and pass around abstract types (and interfaces!)
did you try playing around ?
how else will you learn
fuck around and find out
ye
ok
Oh so if I just put the InventoryItem itself as the return type, if one of the inherited classes override it, would it then return that classes own type?
you can't override return types
right, so I can't just override the method and have it return the correct type
this is where generics can help, but honestly not worth the hassle
I don't really know of any other way I can achieve this
well if you put BaseClass as return type then you can Put DerivedClass as returned object
Would I then be able to access a variable that is only located in the derived class from that?
it sounds like you eventually need to do some type comparison so if there is specific methods that only exist on the most derived type, then it will require you to do those operations
if whatever is reaching out to the DerivedClass knows what type it is then yes