#š»ācode-beginner
1 messages Ā· Page 596 of 1
sounds like the zombie chase is in wrong axis
how do i fix that ?
ok
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if (Input.GetAxis("Mouse ScrollWheel") < 0f ) // forward
{
Camera.main.orthographicSize++;
}
else if (Input.GetAxis("Mouse ScrollWheel") > 0f ) // backwards
{
Camera.main.orthographicSize--;
}
Currently I have this as my code, but it seems to be really.. temperamental? I'm trying to "zoom out" of my 2d game, but I have to scroll down on my mouse anywhere between 5 - 50 times just for it to scroll out
I'm not sure why, either, could anyone please give me some advice
I would start by switching to GetAxisRaw
https://paste.mod.gg/mxkvcoejlvtq/0
here is the code for the zombie
A tool for sharing your source code with the world!
thank you, It turns out all I had to do was change it from being in FixedUpdate() to Update(), i guess fixedupdate works differently to how i expected it to šæ
Oh you didn't mention that. yeah input needs to be handled in Update, not FixedUpdate
ortho size is a float so you can do:
camera.orthographicSize + (Input.GetAxis("Mouse ScrollWheel") * multiplier);
oh lovely. thank you
Yeah thanks, I'll keep that in mind for the future.
@bitter apex and to make it go backwards do (1f - Input.GetAxis("Mouse ScrollWheel")) * multiplier
no wait it should be axis * -1 mb i forgot its from -1 to 1
that's not right - you'd just multiply by -1
Did you take the NavMesh surface off of the zombie like we said yesterday
yes
And your zombie no longer had a rigid body?
yes he no longer has that
And is the animator on a child object, rather than the one the NavMesh Agent is on?
now it is
Okay and did that solve the problem
let me try
a warning and an error
Failed to create agent because there is no valid NavMesh this is the warning
this is the error
MissingComponentException: There is no 'Animator' attached to the "ZOMBIE" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "ZOMBIE". Or your script needs to check if the component is attached before using it.
UnityEngine.Animator.SetBool (System.String name, System.Boolean value) (at <9b89611000504a9585efec19be4faf3b>:0)
ZombieAI.Update () (at Assets/scripts/Zombie AI.cs:60)
well i did create an empty child to put the animator in
First error: We already covered this. You need a NavMesh Surface for a NavMesh Agent to be on.
Second error: You need to drag in the animator that you moved to a different object and remove the get component calls to it
you know what , i think before i go on with this project i should do a unity basics course and a c# basics too
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
why is it that even though I set previousItemX as inactive, it still is active when I play? I wanna be able to only have one object from each category active
First off, if you ever find yourself numbering variables, you should be using an array instead.
Second, show the inspector for GameManager
lord..
ā ļø
So, those first 9 things - are those prefabs or objects in the scene
when you click on them, what highlights
Prefabs
No Iām disabling the Actual (item) s
Those prefabs are destroyed in update
Those work
So are the objects in the inspector prefabs or objects in the scene
Top 1 to hair 3 are prefabs, actual top 1- actual hair 3 are game objects
Ah, wait, I see, you've got separate variables for the prefabs and the instances.
Yes
This is part of the reason you should be using collections, easier to read
Will take note for future projects, still quite new to this
They're re-activated by the wearClothes method, which is being called from somewhere else, for now, just put return; as the first line of it so the rest of the function is skipped. Do they all start up deactivated then?
I thought you canāt put return in void functions?
ofc you can
Whaaaat
it just returns early without any value
Ohh
Do I do the same to wear clothes 2 and 3?
Iāve learnt arrays, just didnāt think of using them lols
i dont get it are these not the exact same return type? whats the issue
yeah once you're adding numeration to your variables, its def time for an array
It says unreachable code detected
Yes ignore that
the tuple?
Make a class or struct for this, don't use a tuple as a list parameter
Oh but wonāt nothing happen then
Yes, that's the point
We want to disable these functions and see if Start is actually deactivating things
why are you using State in the definition of the interface?
so we're removing the code that reactivates them
Ohhh
Is that a completely different State?
state is a class that inherits fro mthe interface istate
When I click the objects nothing is activated
Well, yes, that's what is to be expected with the functions disabled. But everything's now properly starting disabled, right?
Yes
so any IState must expand into a list of State?
rather than into a list of IState?
So, it seems one of those WearClothes functions is being called on startup, which is why there are some that are active on start
is this a me thing only orr
click Explor out LEarning pahways
what's the URL you're at right now?
Seems like it
this is the junior pathway
cant start it
getting 404
paste the exact URL you're trying to access
clear your browser cache
ye it would be helpful if i can do it this way
its working now rebooted router
a nice flush of DNS works too
unity has changed some links around and caused massive headaches
None of them are active on start, the functions are only called when I click on something during playtime, just that when I click multiple items it doesnāt destroy the item I clicked before
This compiles just fine.
Make sure that you have the correct State
Okay, your initial problem said they were active when you hit play, so that was the problem I was trying to solve
Ohh sorry I shouldāve worded it better
I don't see one in UnityEngine.UIElements or System.Collections.Generic, but maybe you have another State defined in the root namespace
Which is why I suggested using a struct instead of a tuple, the compiler wouldn't let you create one with the wrong type of State and it'd be easier to see the root of the problem.
tuple is just a lazymans struct anyway
So, what, specifically, is the problem? It's not disabling the old ones when you're trying to change?
So when I click an item it activates it in the scene, and it stores the previous activated item in previousItemX, which I then deactivate. Problem is thatās not working
Try logging the item before you deactivate it and see if it's the one you expect
Sorry, whatās logging?
printing a log.
Like Debug.Log
Oh debug
Okay
im working on this game where theres this like little companion that follows me around and it pretty much works but when i actually start the game the character follows me but also flys in my direction. When i add a rigidbody it somewhat fixes it but the character just starts glitching out and "thrusts" into me. how do i fix this?
how can we know if you don't show the code
also send !code as link
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oops also heres the tutorial i used https://youtu.be/zssU0MZcIx8?si=xJGffJDdmK8bH82B
using UnityEngine;
public class AiFollow : MonoBehaviour
{
public GameObject ThePlayer;
public float TargetDistance;
public float AllowedDistance = 5;
public GameObject TheNPC;
public float FollowSpeed;
public RaycastHit Shot;
// Update is called once per frame
void Update()
{
transform.LookAt(ThePlayer.transform);
if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward), out Shot))
{
TargetDistance = Shot.distance;
if(TargetDistance >= AllowedDistance)
{
FollowSpeed = 0.005f;
TheNPC.GetComponent<Animation>().Play("Jogging");
transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, FollowSpeed); }
else
{
FollowSpeed = 0;
TheNPC.GetComponent<Animation>().Play("Breathing");
}
}
}
}
#JIMMYVEGAS In this Mini Unity Tutorial we show you how to create a script which will make an NPC follow you like a companion.
⦠Subscribe: https://goo.gl/gidCM5
⦠Patreon: http://patreon.com/jimmyvegas/
⦠FREE Assets: http://jvunity.com/
⦠Facebook: https://www.facebook.com/jimmyvegas3d/
⦠Twitter: https://twitter.com/jimmyvegas17/
----------...
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
as links mate
anyway moveTowards is probably not a good way to implement this. either way, seems your Y axis aren't level
if player origin is at 0, 5, 0 and the companion is at 0, 2, 0 it will float to 0,5,0
you probably want to use a Navmesh agent though,
if you ever encounter a wall between you and your companion it will just phase through the wall
uh how many lines on average should an AI be
there is no number
whatever amount required
alright was just asking where the line goes between rididucilously long script and normal script
im making an AI for my game (my first game that is)
its currently like 200 lines
202 actually
but aight thanks
the line count only matters for your readability it makes 0 difference in the end code
also should i change it into FixedUpdate? because i set it as 0.02F but sometimes its faster and other times its slower without me changing anything
to make my code more readable, do i place all variables of one sort, for example public ranges and the privates next to each other
Becasue right now my code is a complete mess with functions everywhere
thats because you're missing time.deltaTime, look at the docs for moveTowards .
tbh this whole thing is a mess, just use a navmesh agent
you will have a better companion follower that can actually avoid obstacles
organize it however is most legible to you
I typically do
public class Example {
public field
private field;
I rarely have public field just an example, put my public at top like events
i tried something like that with another model and it didnt work but that was prob cause the model wasnt rigged or something
i can give it another try
model and rigging has 0 to do with how a navmesh agent functions
those are just visuals
you can literally slap anything on navmesh agent and it will move it
navmesh agent is just controlling the transform moving it on flat mesh baked areas
i only have this vid from the nav mesh version and the companion just went flying
i gave up on it and did the thing i have currently but i can try again
i didnt show the script or nothin though
already see something wrong
why does navmesh agent have surface on it?
navmesh surfaces are powerful but you dont put them on moving agents..
the tutorial i watched was super old and it had a nav mesh agent and those things used to have the bake thing but then they removed it from the agent no?
so i just added the surface to bake it
things have changed yes
you add navmesh component then you bake it yes, you keep it on a static ground usually unelss you know what you're doing with moving objects.
I suggest you go through this
https://youtu.be/SMWxCpLvrcc
The AI navigation system in Unity allows non-player characters (NPCs) to move intelligently through a game environment by calculating and following optimal paths and avoiding obstacles.
In this video, youāll learn how to get started by setting up a NavMesh surface and how to set up the AI Navigation system package in Unity 6.
More resources:
...
thx
this is from unity so you know its good
Does anybody by any chance know of a tutorial to add a character with animations to a first person game with the ability to see your hands and feet? I am currently using just a capsule with my own player movement script. But I cant seem to figure out how to switch the capsule to a character model while also allowing it to move with my player script.
your movement code what does that have to do with visuals
one shouldn't impede the other
so idk what this means
how to switch the capsule to a character model while also allowing it to move with my player script.
unless you have animator set to drive root move transforms the animations are just visuals they don't touch movement
apply some mixamo animations or something to a child object that has the humanoid rig
just make sure your animator states match your script actions.. if your script is moving your controller with speed then start moving animation etc.
If I want to pass a enum parameter to a method from another class, where do I have to declare the enum?
wdym declare it in any file
In the class calling the method, in the class that has the method or in both?
Anywhere accessible from both places
if you nest the enum definition in the class then you need to preceede it with that class if you access it from else where
If you have an enum you should be able to just put it in the parameter
Mmmm, I see
I basically want to make like a script that is basically a status effect that other classes can generate upon different targets, and I wanted to have like a enum to identify the stacking method
So I guess I should have the enum in the class that generates the status, and reference that on the status itself
i always put enums in their own files
So, if you make the enum inside of the class then you need to append the class type onto that enum
You can just make an empty script and just have the enum there. Then any class can call it
if you have a namespace, you can toss it onto that and use it everywhere in that scope without having to append the class type onto it
well, you can also do without a namespace inside of a 'global' scope, but I suggest always including a namespace anyway
basically if its defined in another class you are doing
public class Foo{
public enum MyEnum { x, y, z }
public void MethodWithEnum(MyEnum val){
}
}
public class Bar{
private Foo foo = new();
void Method(){
foo.MethodWithEnum(Foo.MyEnum.x);
}
}```
Should only be using nested enums within the class itself anyway. If it's being used elsewhere then stick it on a more outer scope
wdym "enum ref"
What's the enum called and what does it correspond to
They need to know what the enum means
The enum is called in the initialization of a status effect, to check what it should do in relation to other status effects
In like, if they are the same, do they just happen togheter? Does the more recent one overrides the other? Does it reset the duration of all status of the same name?
namespace ProjectName
{
//UtilityScript.cs
public enum StatusEffect
{
Blind,
Freeze,
}
}
namespace ProjectName
{
public class Skills
{
public StatusEffect StatusEffect;
}
}```
Simplified idea
why can i not get a gameobject from a scrollview?
Ideally you do split the namespaces up a bit more, but that can be a little confusing unless you've the idea how to group everything.
Like I would have a Entity namespace, Stats namespace, ect
why not
So I make those enum in like separated scrip on the namespace of the whole project?
scrollview is just a component, the gameobjects are on the child
u got a class named Props?
oh
uh no
Not a requirement, but usually not the greatest practice to let stuff hanging out in global space. Buttt if you're the only one working on the project it matters less.
I mean, that seems like something I would want to have access from anywhere on the project
Yeah, until you install a plugin and they have the same class names as you. WHICH they will have their own namespace unless they want to piss people off
just just make a field for it
ok
put your item in the slot and you're done
Am I even using classes there?
your classes become wrapped in the namespace
But this would not include any class right? I would just state at the begining like using ProjectName and I would have access to the enum, isn't it?
Without the namespace, if you made a Enum then you can access it anywhere without any extra syntax*. I'm just saying that it's good practice to use namespace because imagine if you wanted to make a class called Image, but then you run into a problem that Unity also has a class called Image... how do you identify which one is yours?
Doens't it warn you when you do that?
It does, but if Unity didn't wrap it in Unity.UI namespace then you couldn't make a class called Image yourself in that global space.
oh eew
welcome to .net 4
when core CLR drops we will have modern .net & c#š¤
nice when will that be
hopefully unity 7
So.... something like this would be fine to use?
Well, the namespace would include all classes that want access to those enums
Like as an example above if I had a Skill namespace then I'd include all scripts that deal with my abilities and need to share those enums among each other
So... in any class that I use the using ProjectGeneralEnums, it would become wrapped by the namespace then?
Any class that wants to use those enums you'd wrap into the namespace, otherwise you have to #Include 'Using' it on that file or explicitly state where those enums comes from
I think of namespaces this way:
A namespace is just part of the type name. Your full type name is ProjectGeneralEnum.StackingMode But if you put using ProjectGeneralEnum you can just write the short version StackingMode
So when you want to use that enum you either write the full name ProjectGeneralEnum.StackingMode or you do using ProjectGeneralEnum so you can just write the short version StackingMode
And if it's all in the same namespace then you don't even need to use 'using'
Wrapping enums into its own namespace is something I've seen too, but I like to group classes who use those enums together.
So I basically just created a thing I can call from anywhere like any other method implemented in base unity right?
As what you provided, if you don't wrap anything else in that namespace then at the top of the scripts that need to use those enums you'd have
using ProjectGeneralEnum```
As stated by PraetorBlue
There's nothing special about it being in a namespace. It's just part of the name. Any class can be referred to from anywhere with or without a namespace
The only barrier to that would be if they're in different assemblies, which is a whole nother topic
I just stink at naming stuff and I will run into reusing enum names, so without namespaces it wouldn't be possible
so I have the same error as yesterday, see screenshots with error and code:
I don't understand why. I referenced the class and the object in the inspector
there's nothing on GameObject called play
but there is
so it's clear you would get an error writing Play.play here
GameObjects do not have a function called play
no there isn't
ok I will show you the script for that one
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.html
Nothing here called play\
the script is irrelevant
your variable is a GameObject
not whatever script you're about to show us
omg I'm an idiot
if you want to reference a script, you need to use that script's class name, not GameObject
I was referencing the object, not the class
that's why
sorry, I'm just a little bit mentally impaired
Didn't this happen yesterday?
yes it did lmao
yesterday it "fixed itself", maybe that's what happened
that's what happens when you name them the same thing
so i tried making a gun that the player can pick from the ground and use it , the problem ? the player just walks into the gun like it dosent exist
i will show you the code soon
this is a script for the gun be picked up
https://paste.ofcode.org/MMtB8zviCHLXqvDx9XNK6k
this is the weapon management
Show the inspector of this object
Put a log in the top of OnTriggerEnter and log other.gameObject.tag and see what logs
sorry if this sounds stupid but you want me to do this on the console right ?
That is where logs tend to go
guys i have a question how do i add custom meshe to my player
Add a MeshFilter if there isn't one, set the mesh to the one you want, and add a MeshRenderer if there isn't one
this is pretty vague
do we need t o have a mesh or can i import a fbx file from blender and use it as a player
That is a mesh
when i use that mesh the camera doesnt align with it looks odd
its like i put the camera where it is and its like MILES OFF
This is an entirely different question
Does your mesh contain a camera
no
If so, remove it
Then adding a mesh would have no effect on the camera whatsoever
is it possible for you to join vc with me so i acn show you its really hard to explain
no
you're asking a series of questions that make no sense
okay listen let me rephrase
its hard to explain
Are you trying to import a rigged model into Unity to use as a player model?
an fbx rigged and everything
yes
what weāre having trouble with is adding a custom mesh
and when we just use the base fbx
i don't know what "custom mesh" and "base fbx" means here
the camera doesnāt allign with its position
you know how you can add a mesh renderer
And what are you doing to attempt to align it
Why do you need to add extra mesh renderers?
Are you trying to, say, put a hat on the player?
we tried aligning it manually
it didnāt work out
Explain your actual problem, not your attempted solution
it turned out so weird
Cameras don't do anything on their own. If you want it to align with something, you have to actually do something with it
we have that code already
but it seems detached from the player
its really hard to explain
Maybe show a screenshot or something
IS IT possible for us to vc so we can show you because i cant really explain this well
no
you need to coherently explain what you're trying to accomplish and what is happening
So far you've just said "custom mesh", but I have no clue what that actually entails
are you trying to completely replace the player model?
There are no voice channels in this server
itās actually so fucking hard to explain trust me š
are you trying to attach an object to the player?
Then you haven't tried to explain.
Tell me what you want to make your game do.
Do not include anything technical whatsoever.
Simply describe what the end-goal is.
we want the camera to be attached to the player in a first person perspective
basically i followed a tutorial for a player camera for a fps game and he(YOUTTUBE GUY) used a capsule for the player model and i mwondering why when i imported my palyer model from blender and replaced the capsule the camera is disconnected from the body
does that make more sense
Okay, so you used to have this:
- Player
- Capsule
And now you have this
- Player
- Some Model
yes
and the capsule
the camera works perfectly
but the model that we use
the we made
the camera is misaligned
Is your model actually in the right place
yes
elaborate
ensure that its local position is zero, yes
or maybe not i think it is
If your camera is pointing at a position, is that position where you'd expect it to be on the mesh
nope
like, if you want it to point at the center of the object
is the center of the object where the camera is set to follow
okay so if i move the camera to the playerās head itās not even attached to him
we see it from a third person pov
yeah
then move the object so that it's where the camera is following
how? it says the camera is on the model
Did you parent the camera to the model prefab directly?
obligatory "use cinemachine"
yes
Then move the camera
That's going to make the camera sit in a fixed location relative to the model prefab object
ohh wait
It's not going to care about anything that the model is doing
the camera
put the camera in the correct place instead of the wrong place
yes\
This is why screenshots would be helpful
So we don't need to ask a bunch of questions about what objects are where
Okay, so, playerCam is not a parent or child of the mesh at all
yeah according to the video it makes it less buggy? if it would help i could send you the video i followed
So, it seems like you just want to move either it or the mesh so they're where you want them to be
note that CameraPos is pointing backwards
when we do that it moved so weirdly
the blue arrow is the forwards direction for that object
we move the camera slightly frontwards it goes a million miles front
I don't even know what cameraPos is doing
It has no scripts
and no one's posted any code
so I have no information as to what that object does
camera pos is where its supposed to be
Okay, so then you should move that object to where you want the camera to be
i did
Okay, so you want the camera pointed out of the back of this guy's head
How about show the !code of what moves the camera
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
alright
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
private float xRotation;
private float yRotation;
// Start is called before the first frame update
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
private void Update()
{
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0,yRotation, 0);
}
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
huh?
The bot tells you how to post code
alright
Don't scale mouse input by Time.deltaTime. Learn why...
I wanna write code that parses this into a Json and parses Json into this. I know that SO can't be parsed into Jsonsā should I turn it into a Monobehaviour, or should I add a "dummy" Monobehaviour to parse this into and then parse it into a json and vice versa?
ToJson should work on any Unity Object
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/JsonUtility.ToJson.html
https://paste.mod.gg/kqqqqawpvbyc/0 like this?
A tool for sharing your source code with the world!
Yes.
POCO is fine - no need to make a MB or SO
MB or SO will make it more complicated
What's POCO, sorry?
A tool for sharing your source code with the world!
Okay, nothing in this has anything to do with the player. This code just rotates the object it's on (and an orientation object) based on the mouse
Yes!
put all that dataq in a regular serializable class
Ah, this one moves it
and just make that as a field on the SO
honestly wish i knew what your talkinga bout the video does explain it slightly but i only have a rough idea on how it works
So, every frame, you teleport the camera to this object's position, and you rotate the camera based on the mouse
wouldn't that just spit out an instance ID
oh i see
i still dont see why its not worki ng?
Meaning the end result is, you should have a camera that is fixed inside of this mesh's head and spinning around as you move the mouse
Aha
Where does the camera actually end up
nah, only references to other UnityEngine.Objects are serialized as their instance ID
A capsule is radially symmetric, so it was not possible to tell that the capsule wasn't rotating
the first image\ shows how the camera looks like
Ah, right.
The object itself can still be serialized meaningfully.
Can you show the cameraPos object from more than one angle
ill try my unity is all jumbled up rn
Ok ok bet
im not sure if this is what you meant but here
Okay, so, if there is no other code involved in movng the camera, with what you've shown, there is no way that this code could result in the camera angle you showed
Which object has PlayerCam and MoveCam
well uh those are the only 2 pieces of code i wrote
Your camera is offset from the MoveCam object
It will always be this many units away from the camera position in the player:
Which is to the left and in front, and slightly above
wait so i just need to change the position of that?
Much like this camera angle
sorry i dont really understand
Yes
Since you are moving the parent object to the cameraPos object, this object's position will be the offset from that the camera is in
this had nothing to do with the model
The position you see in the inspector is how far away the object is from its parent
but this seems aligned with the model?
im sorry if im a bit slow
What is?
so i should make allt he positions 0?
X is left/right
Y is up/down
Z is forward/backward.
So, the camera is 2.82 units to the left of the guy's head, 1.47 units above the guy's head, and 2.87 units in front of the guy's head
Assuming you want it to be at exactly that position, yes
ohhhhh
wow
okay
yeayh it worked
If this object's position were 0,0,0 then it would be at 0 units to the left, 0 units above, and 0 units in front
which would mean it's at that object's position
how do i make a weapon switching system , you know like most fps games
that depends quite a bit on what a "weapon" even is in your game!
Change out the model you're rendering, and what kind of prefab your gun shoots
Okay, I know this is like a pretty rough ask, but since this feels like extremely hard to test out for all cases. I would love if some of you guys could check this to see if I made like some kinda of superobvious msitake https://pastecode.io/s/zz6o2woj
oh man, status effect stacking
i remember doing this extremely wrongly about eight years ago
i want something like quake or doom
does your game have any weapons at all right now?
at its most basic level: get rid of the current weapon, then create a new weapon
Status effect stuff is hard
You'd think coroutines be fine but sometimes you want to remove specifics and that's such a pain
It's the stacking of a mixture of different effects that gets really annoying
when they have different rules (possibly multiple rules on different instances of the same effect)
Well, having a good GDD fixes a lot of problems too ;p
knowing me I don't know what the heck I want most of the time
yes a pistol and im trying to add an assault rifle , but i as of now i cant make the player pick up the assault rifle and switch it with the pistol
I do know what I want, I don't know how to code it properly half of the time lol
perhaps you can start by just completely throwing out the pistol
I'd wouldn't make it too complex and just get basic stacking with refreshing on application if anything then append to it later
What defines a pistol
what scripts, assets, etc. make up the whole of "Pistol"
well i made a universal script for all weapons , and a model for the pistol and another one for the rifle
So, it sounds like you just wanna disable the pistol model and enable the rifle model. Then do whatever your script does to be a different weapon
yes and be able to swap for other guns the player find in the game
im having some trouble with that
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.ofcode.org/LnndkLLepUC9N7k6Jd5aKg https://paste.ofcode.org/DrY3Qf4VQeaq5zdZWKKnFq does anybody know how i could make the main controller the singleton and make the functions available like this: MainController.Instance.SoundManager.<any public functions>; idk what im doing wrong
thank you
code for the weapon pick up https://paste.mod.gg/ldrtwifzhxkt/0
A tool for sharing your source code with the world!
weapon manager https://paste.mod.gg/wgnchxgagnpw/0
A tool for sharing your source code with the world!
weapon scritpt https://paste.mod.gg/ihrcgpruzbqb/0
A tool for sharing your source code with the world!
fun fact about paste.mod.gg, you can add multiple files to a single post
also did you ever bother confirming that OnTriggerEnter is being called?
im gonna be honest with you , i dont know how to do that
this page is based 9/10
Debug Log should literally have been the first line of code you ever wrote
funny isnt it
nah i push it directly to an active Command panel
i have made a custom button on the inspector, this button is the only thing doing ,beware this is SOLELY on editor mode only, it will NEVER be in runtime mode:
- clean up collection A
- instantiate linked prefab, not unlinked instance
- populate collection A with those prefabs
- populate collection B with collection A
all this steps are in a single function, and it wont be called by anything in runtime or editor mode unless inspector button is pressed
now i gonna show u guys how i populate both collection
this is collection A , A is a Dictionary<GameObject,contentType>
private Dictionary<GameObject,contentType> allGameObjects = new();
public void RebuildContent()
{
allGameObjects.Clear();
if (hasSubTitle)
{
GameObject spawnedObj = Instantiate(prefabs[0], transform);
#if UNITY_EDITOR
PrefabUtility.ConvertToPrefabInstance(spawnedObj, prefabs[0], new ConvertToPrefabInstanceSettings(), InteractionMode.AutomatedAction);
#endif
allGameObjects.Add(spawnedObj, contentType.Subtitle);
}
foreach (contentType element in spawningElement)
{
GameObject spawnedObj = Instantiate(prefabs[(int)element], transform);
#if UNITY_EDITOR
PrefabUtility.ConvertToPrefabInstance(spawnedObj, prefabs[(int)element], new ConvertToPrefabInstanceSettings(), InteractionMode.AutomatedAction);
#endif
allGameObjects.Add(spawnedObj, element);
}
..... <- populate collection B```
this is collection B , i made "a list of lists" , because i need to show it on inspector i need to chain them as serializable
[Serializable]
public class AllStepObj_Value
{
public List<GameObject> Objects;
}
[Serializable]
public class AllStepObjMap
{
public List<AllStepObj_Value> Steps;
}```
this is how i populate it
int counter = 0;
objMapper = new();
objMapper.Steps = new(new List<AllStepObj_Value>(){});
objMapper.Steps[0].Objects = new();
foreach (GameObject element in allGameObjects.Keys)
{
objMapper.Steps[0].Objects.Add(element);
}```
all of these scripts did not involved "execute in edit mode", as they are fully driven by inspector button events
by pressing the button, it will do something like this on inspector
objMapper (collection B) , is actually populated like the code
but if i ever move to other scene and come back, all stuff i populated on objMapper will disappear
why tho?
assigning it by hands , dragging objects will reserve across scene, but not code ?
did you mark the object as dirty?
whats this?
seems like a visual studio issue not related to unity
if(GUILayout.Button("Rebuild UI"))
{
Undo.RecordObject(parent, "populate objMapper");
parent.OnRebuild();
PrefabUtility.RecordPrefabInstancePropertyModifications(parent);
}```
i used undo instead of setdirty, it seems better
this is on my custom editor script
worked , ty š
Is there any reason an if statement with the condition that a certain boolean is true can evaluate to true but nothing inside the if statement actually runs? I'm so stumped, I've put debug logs everywhere and everything up until the boolean changing from false to true happens, but nothing inside the if statement runs. I've checked and there are no spelling errors.
are you attempting to drag a scene object into a prefab?
I am trying to assign a component of a child inside the prefab into a script on the prefab
actually have you saved your code? because the slot shows TextMeshPro rather than TextMeshProUGUI
I did, yeah
Oh, unless it's not compiling cause I have an error in other script wait
(also, you can generally just use TMP_Text)
textmeshpro is different from UGUI, one is solely UI , one can be instantiated in world space
any compile errors will prevent all of the code from compiling
TextMeshPro and TextMeshProUGUI have largely the same interface
i'm actually not sure what would differ from the outside
they are very close
(hence why I always just use TMP_Text)
just import TMPro yes
and then u can use TMP_Text
that's a given for any textmesh pro type
Doing a .Clear() on a dictionary is pretty much the same than just assigning it a whole new blank Dictionray right?
No.
- if there are other references to the dictionary, Clear() will be visible to them. Assigning a new dict to this reference is not.
One clears the dictionary, the other allocates and assigns a completely new instance
What do you mean visible?
And what's the difference betweena a cleared up dictionary and a new isntance of it with no data?
I mean accessing the dictionary through those references you will find it has been cleared
If a dictionary has previously been populated it may have grown, resizing its backing arrays to accommodate the data that was previously assigned.
Clearing that just resets that data, it remains allocated.
A new instance is unrelated new data that's only referenced where you newly assign it, and will have to reallocate space as it grows
So if I am making a new instance I am... liberating space?
If the previous references to the old dictionary are set to null, sure. But whether it's liberating for a good reason or not is usually the driver to whether you new or clear
I mean:
Dictionary<string, string> a = new();
a["hi"] = "hello";
// b is now another reference to the same Dictionary
Dictionary<string, string> b = a;
a.Clear();
Debug.Log(b.ContainsKey("hi")); // false
a["hi"] = "hello";
// here we reassign a to a new dictionary
a = new();
// b still points to the old one
Debug.Log(b["hi"]); // prints "hello"```
if it's just gonna regrow then deallocating is a bad idea because garbage collection and allocation is not free
Would b update to a dinamically there? wouldn't it just be a copy?
it's not a copy
they are both references to the same underlying object up until the part where a is reassigned
that's why we call them references
THere's only one dictionary
we are clearing the one dictionary
so both references can "see" the changes
Yeah, but wasn't your reference to a snapshoot of the state of the dictionray at one specific time and therefore not changed?
no.
There is no snapshotting
both references are equal references to the one existing dictionary
That's the difference between a value type and a reference type
If it was a value type object, for example a Vector3 or an int, then it would behave as you say
I have read that like 10 times I do not understand it. Like how can I even tell them apart?
What if a wanted a snapshot of the DIctionary?
var copy = new Dictionary<ExampleKey, ExampleValue>(otherDictionary);
You would make a new dictionary and copy over all the values.
What vertx wrote just above me does that
note that when you want to actually create a new separate object we must use the new keyword
there's nothing to tell apart, again they are the same object.
A reference variable (such as a and b in my example) is nothing but an address or pointer to a location in memory where the actual object lives.
Why declare it as var and not as Dictionary?
in this case, both addresses are the same
because my wife is sleeping on my arm and it is less typing
wait
sorry I didn't lol, only vertx did
it's less typing is all
@frigid sequoia https://media.giphy.com/media/xUPGcLrX5NQgooYcG4/giphy.gif
var copy = new Dictionary<ExampleKey, ExampleValue>(otherDictionary);
Dictionary<ExampleKey, ExampleValue> copy = new Dictionary<ExampleKey, ExampleValue>(otherDictionary);
Dictionary<ExampleKey, ExampleValue> copy = new(otherDictionary);
They're all the same, who cares how you write it
otherDictionary.ToDictionary() 
I hate that gif, why coffee, something that makes no sense to have a copy or reference of
At least it explains the semantics, but yeah it makes me feel ick š
y'all already explained it, some visuals reps would defo help
no need to say the same exact thing... waste of breath š
Yeah, I understand the concept, I just don't understand how it works
I think of reeference variables as pieces of paper with addresses written on them. With the object being referred to as the house. itself
a = something; changes the address written on a
a.Clear() actually clears out the house at the address
so if a and b hold the same address, clearing out the house at address a will also clear the house at address b
since they're the same house
that would not be true in the case of
Dict<T> dict = new():
Foo(ref dict); // that pass the address, not reference
So if I do this b would remain as 1 no matter what I do to a
I hate to say this but learning C is easiest way to understand
What if I don't want it to?
This doesn't change the analogy... this actually passes a reference to the piece of paper
yes because int is a value type
assuming a was 1 when the emthod was called
You could wrap it in a class and refer to the variable in the class, because the class is a reference type, passing the reference around is just passing around that address
So... if do like this u mean????
hello, do i still need Time.deltaTime in an IEnumerator? Image is start of IEnumerator function
end of function
!code
š Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You need Time.deltaTime when you need to convert a per-frame quantity to a per-second quantity. Whether that's happening in a coroutine or not is irrelevant
public class SomeClass {
public int Value;
}
public SomeClass A = new() { Value = 1 };
void SomeMethod() {
SomeClass b = A;
b.Value = 2;
// a.Value is now also 2.
}
alright
well this seems to be not working correctly:
transform.localPosition = transform.localPosition+new Vector3(velocityX * Time.deltaTime, velocityY * Time.deltaTime, velocityZ * Time.deltaTime);
what about it isn't working
what are you expecting it to do
and what's happening instead?
Where is this code?
and normally without Time.deltaTime its moving normally fast
You need to show the full context
wym?
alright
not just a single line
Ufff, I think I understand, but feels like the thing I would do without wanting to and would fuck me all over
Like do I have to know which ones do that of aiming at the same memory space rather than snapshooting?
Yes you have to know but it's a very simple rule. If the type is a struct, it "does the snapshotting" i.e. it's a value type
if the type is a class, it's a reference type
I feel this was pretty well explained in the resources linked
Maybe for you
I read that I am like "what?" on each other word
Then please ask questions about what you don't understand, pointing to the paragraph in question
It's not anything in particullar
as if the resource I've written is not enough I would like to improve it instead of just having endless pointless rehashings of things it already explains
It's like reading about a subject u don't really understand yet and you are like "wait, what was that again?" you know?
Like I dunno, I guess I am used to textbooks where 90% of the words are like actual filler
But I just understand something a thousand times better with a single practical example than reading the documentation 100 times
how do I reference a script from a different script
Create a public or serialized field and drag-drop the other object with said component-script into the field from the inspector
yup just found a 1 min tutorial, cant believe i didnt think of that
If you're needing a reference during runtime, when you instantiate the object you'd pass a reference to the instantiated object
Can someone help me. I need a script that plays object animation on play trigger enter
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #šāfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Look up the OnTriggerEnter method and Animation.Play. WHen the method is called, verify the object using its tag and call the play method.
hi i'm messing around a prefab i installed on asset store, and i'm trying to get it moving, but only its outline moves and not the object itself. does anyone know why
the script only moves the parent object so far
Hi does anyone have an idea what my be wrong with by character? I added a camera to follow it, but there seems to be a flickering in animations. I tried to record it, but it seems fine on the recording. Before I added the camera follow it was fine too.
is your character a rigidbody without interpolation turned on?
if that's the case simply turn it on interpolate, if it's not you should probably share camera movement code
Oh yes thank you, that was the problem
I don't really know what that interpolation means
yep, everyone getting bumped onto this issue
interpolation is when the value getting calculated between other values, I guess?
anyway
this specific case it means that gameobject is still moving inbetween physics frames
now it would visually lag one physic frame behind it's actual position, as a drawback, but it's almost always is fine
if it's not fine extrapolate exists but it can create another problem where the object appear further than it actually is within same 1 physic frame error
there are 50 physic frames in one second by default
but you can have more than 50 fps in one second
if you happened to get new visual frame without getting new physic frame
physically moving objects like rigidbodies won't move
and that would make an illusion of lag
if you pay close attention and have high fps you might be noticing it
it usually only a noticeable issue if a camera following such object
interpolation on rigidbody would add fake movement in between physic frames so it always move somewhat smoothly
fake in a sense you can't get collisions and stuff on such fake movement frames
i have a doubt, so i am making a 2D game where you can interact with the building to go in the building, but so many different buildings are there, should i use the load Scene method or anything better i can do here
who knows what's going on with asset store assets
I don't think there are issues on the video I can spot, rather than if you move not the train but something else, like only it's collider idk
you may consider keeping buildings out of bounds and teleport player in and out of them? idk
it's a general gamedesign question
is they are small and there is alot of them teleporting seems better, if not scenes
ahh I see
thanks for the explenations and for the help
have a good one
How do I make my speed boost properly follow behind my player and not rotate with the player
try simulation space global
so particles no longer exist as player transform childs (kinda)
tried that still the same issue
global space is correct to prevent them rotating after instantiating, but you need local direction upon instantiation to rotate them at the start
How does order of execution work with unity? For example will it wait for an entire Start() function to complete before mvoing onto the next, or do they happen semi in parallel? Same thing with stuff like FixedUpdate(), im getting some inconsistencies with my code and im wondering if that is the cause
they are all executed one after another on the main thread. you can customise the execution order for monobehaviour events or you should manage executing methods yourself in an order you prefer.
i see, ill look into that, thanks
using UnityEngine;
public class BallController : MonoBehaviour {
public float speed = 10f;
private int _scannerLayer;
private Rigidbody2D _rb;
private void Awake() {
InitializeRigidbody2D();
InitializeScannerLayer(7);
}
private void Start() {
_rb.linearVelocity = _rb.linearVelocity.normalized * speed; //set linear velocity
}
private void OnCollisionEnter2D(Collision2D collision) {
var normalizedVelocity = _rb.linearVelocity.normalized * speed;
_rb.linearVelocity = normalizedVelocity;
if (collision.gameObject.layer == _scannerLayer) {
Debug.Log("Ball detected colliding with scanner. Destroying Ball.");
DestroyBall();
}
}
private void DestroyBall() {
Destroy(gameObject);
}
private void InitializeRigidbody2D() {
_rb = GetComponent<Rigidbody2D>();
if (_rb == null) {
Debug.LogError("Ball Rigidbody component is missing on game object.");
}
}
private void InitializeScannerLayer(int layer) {
_scannerLayer = layer;
}
// Update is called once per frame
}
In oncollision2D in the if statement condition it always evaluates to false even tho I had already set up the game object layer properly on the unity inspector, I've tried everything it still doesn't work
Debug.Log($"{collision.gameObject.name} collided, it has layer {collision.gameObject.layer}, scanner layer is {_scannerLayer}");
Put this outside the if statement and show what it prints
- Decide if you want gravity
- If you do, simulate gravity yourself in your code.
- Optionally use the SimpleMove function instead of Move, which has built in gravity
Almost any tutorial with Characteracontroller will cover how to simulate gravity though
i see
hey everyone, currently i have spawners in my project that spawns an enemy, how do i make it spawn a different enemy after a certain time?(the game is a plane shooter)(i have the timer set on a different script)
Use an if statement?
Or put the things you want to spawn in some kind of list that you iterate over?
The question is pretty vague
i know the method but idk how to implement it
like how do i change the variable inside a script midgame?
wait
i think i figured it out
With the = operator
yeah that š
I switched to VS Code since it some auto completes for my code, but it seems like I'm still missing a lot of options
This is what I get:
these I don't see
I followed all instructions from here https://code.visualstudio.com/docs/other/unity
but I still can't seem to get all the other options
Do you have variables or classes or methods with those names?
don't have any
Then why would they show up?
No
They're not default
Those are some custom classes and methods in wherever you took that screenshot from
LogicScript is not a default anything
it keeps printing something else
it doesn't detect the collision with the layer I want it to
What does it print exactly
why cant i assign this object to a field of type Camera
should i be using a diff type?
Are you dragging this from the scene onto a prefab?
A prefab cannot reference scene GameObjects . . .
so then how do i do it
Huh? Static fields don't display in the inspector . . .
nonononono, they don't
Show us . . .
static field belongs to the class not the instance thats why
oh wait the editor wasnt updating because my code had other errors
but then what if i want it static
ye i want this shared for all instances of the class
i cant do Camera.main because thats expensive apparently
That's fine. It can be static, but you have to assign it manually via code . . .
You can make the class itself have a static instance
how do i get it from the scene tho
GameObject.Find worst case
no
use a singleton pattern or Dependency Inject it
a singleton makes no sense here
this case I would use a singleton holding references
i mean it doesnt HAVE to be static
it's not great I agree
but it does make my life a lot easier
make it static, make it non static, assign non static to static on Awake?
without explaining the use case is not really productive to suggest anything
fair
ok i just want a draggable object
There are a few methods. Dependency injection works well; when instantiating the object, the script that creates it can have a reference to the object you need . . .
this is what i have so far
public class DraggableObject : MonoBehaviour
{
private bool _dragging = false;
public static Camera MainCamera;
private void Update()
{
if (!_dragging) return;
var mousePosition = MainCamera?.ScreenToWorldPoint(Input.mousePosition);
if (mousePosition == null) return;
transform.position = new Vector3(mousePosition.Value.x, mousePosition.Value.y, 0);
}
}```
i had Camera.main first but thats expensive
all this for a camera?
just cache camera in awake with camera.main
camera.main isn't that expensive as a matter of fact
but ig that works
its the initialization method
well my ide says it is
it used to be
You can't use ?. with MainCamera because it's a UnityEngine.Object . . .
Lazy is a cache right?
it used to be much more expensive that it is these days
? wdym
its nullable
its not
Use Camera.main to get the main camera in Awake or Start . . .
its an artifact from what i had first
Unity Objects cannot be null checked his way
bruh why not unity has so many weird quirks
they are internally handled
so i cant get a NRE?
It doesn't matter. Unity objects do not support the newer null conditional or coalescing operators . . .
Just assign the Main Camera in Awake its 1 time call pretty cheap
ok
After the underlying component is destroyed, the C# object for the
MonoBehaviour remains in memory until garbage is collected. A MonoBehaviour in this state acts as if it is null. For example, it returns true for a "obj == null" check. However, this class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.html
The null-conditional operator (?.) and the null-coalescing operator (??) are not supported with Unity Objects because they cannot be overridden to treat detached objects objects the same as null. It is only safe to use those operators in your scripts if there is certainty that the objects being checked are never in a detached state.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.html
private void Awake() {
MainCamera = Camera.main;
}
ye i got it
wait if obj == null is true how can ?. not be supported; it's the same thing in my head ><
Because Unity overrides the == operator . . .
Game engines are incredibly powerful software, handling a vast number of systems that all need to work together seamlessly. With so many moving parts, there are countless quirks and complexities that make them challenging to fully grasp.
game-engine lyfe
btw i cant get the OnMouseDrag to work properly
like its really buggy
is that like a known thing?
those methods don't work very well
ok so i should just create my own thing with OnMouseEnter Exit Down and UP?
event system has better ones or just make your own raycast behaviour
what im not about to create a full raycasting system
ive always wrote my own drag and drop mechanics using the pointer interfaces
im a beginner in unity T-T
raycasts are built in
and my teacher said the event system only works with UI components
your teacher is wrong
Just use the IPointerEvents . . .
event system works w/ anything w/ a collider
yea ur teacher must not be a very great teacher
you mean the EventTrigger component right?
you can add Physics raycaster and it works with colliders
Graphics Raycaster innit?
Physics Raycaster
ahh ok
I believe graphic is for canvas
perhaps you should show what exactly isn't working
what is the intended behaviour vs what is currently happening?
sure
i already changed it away from the OnDrag though
this maybe a working method of doing it: https://stackoverflow.com/questions/56435180/how-do-i-drag-objects-on-the-screen-using-onmousedrag
one second
It will work, if done correctly . . .
eh it works but if i move my mouse too fast it doesnt
because then it exits
and it stops
are you doing drag and drop? just enable and disable a bool and use update to follow
is there an event to track text changes in textmeshpro?
First of all i cant drag it out of the menu, i have to rregrab it.
Second of all if you move your mouse too fast it breaks
if you're setting the changes to the text, you already can track it. Use an event
well im changing the text from 2 scripts that do 2 different behaviours
Instead of assigning the text: text = "blah", create a method with a parameter and pass in the text. Within the method, change the text and invoke an event . . .
there is obviously more complicated stuff going on here then you're letting off, you are dragging UI items into sprites or they stay as canvas items?
this is the code btw ```c#
public class DraggableObject : MonoBehaviour
{
private bool _dragging;
private bool _mouseDown;
private static Camera _mainCamera;
private void Awake()
{
_mainCamera = Camera.main;
}
private void Update()
{
if (!_dragging || !_mouseDown) return;
var mousePosition = _mainCamera.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(mousePosition.x, mousePosition.y, 0);
}
private void OnMouseEnter()
{
_dragging = true;
}
private void OnMouseExit()
{
_dragging = false;
}
private void OnMouseDown()
{
_mouseDown = true;
}
private void OnMouseUp()
{
_mouseDown = false;
}
}```
im dragging them into sprites
i create a new sprite from a prefab at teh mouse position
on mouse down on the ui element
create a method that you use to change the text only through this component so you can invoke an event while doing so
then i would like to be able to drag it until mouse up
thats why you have to click twice no?
you have to instantiate the new prefab as already set to follow mousePosition
ah
THat fixed it sort of, but now it keeps moving after i release the mouse button
even tho i have the event for it
you'd have to show the code and what you did
public void AddObject(GameObject instance, bool isBackground)
{
gameManager.IncreaseObjectLayer();
var mousePosition = Camera.main?.ScreenToWorldPoint(Input.mousePosition);
if (mousePosition == null) return;
instance.transform.position = new Vector3(mousePosition.Value.x, mousePosition.Value.y, 0);
var prop = instance.GetComponent<Prop>();
prop.SetDragging();
}```
public void SetDragging()
{
_dragging = true;
_mouseDown = true;
}```
and this
so dragging stays true?
apparently
why not set it to false in OnMouseUp
dragging checks if you rmouse is over the object
its meant to stay true when you just rleease the button
but it also checks if mousedown is true
which shouldnt be true as i set that false in OnMouseUP
what does this mean?
is Instance actually static?
^ check that
yes
there you have it: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnMouseEnter.html Every time the Mouse is just Over your object dragging is set to true so its always gonna be true
who made that naming
why is it static though if you have static instance
oh wait i dont need static for the setter
You're accessing currentPoolSize through the Instance field which is an instance of SFXPool. you need to access it straight from the class itself . . .
so OnMOuseEnter is called repeatedly?
if you keep it static it would be
SFXPool.currentPoolSize
well either way shouldnt the exit set it to false and then its not true anymore
untill you reenter it
if u would debug the values ur using u'd understand alot more of whats happening and just Debug in general
When your Mouse is over the thing yes
ok so just to confirm if i understand how this works correctly - get is public, meaning it can be accessed from anywhere, but set is private meaning it cannot be changed from outside the class?
yes
ok thank you!
well idk how im meant to debug this if i need my mouse to test it
tf u talkin about? debugs show in the console window
Debug like everyone else does use Debug.Log
or if you want to see them on Screen you can also use GUI.Label in IMGUI
ive not figured out how to get the consoel window open without an error message showingup
if you have error you should probably take care of those..
no no, i mean i can only open it IF i have an error
cuz then i can click on the error to open it
but if i have no error idk how to open it
you šÆ wanna fix that..
there is separate tab for it
ur gonna have abad time building an entire game w/o the ability to check the console logs
ah
put logs in everything.. every method.. ever function. all that stuff.. then play the game as usual..
then u can watch and pay attention to what logs show and WHEN
it'll šÆ help ur understanding
those are great too..
but yea simple debugs wuld be better in this situation
where ur just trying to observe the flow and whats actually being called
ok nah this works how i expect it to work
you can also do onscreen debugging if you feel brave to use IMGUI
private void OnGUI()
{
GUI.Label(new (0,40,100,25), $"bool {mybool}");
}```
it only calls it when it enters it
true
OnMouseUp doesnt get called
can that not be called if OnMouseDown isnt called or something?
Maybe if you just try simplifing it at first:
{
gameManager.IncreaseObjectLayer();
var mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePosition == null) return;
instance.transform.position = new Vector3(mousePosition.Value.x, mousePosition.Value.y, 0);
}```
Then remove the SetDragging and change the Awake Method:
``` private void Awake()
{
_mainCamera = Camera.main;
_dragging = true;
}```
And lastly, also remove OnMouseEnter() and OnMouseExit()
Dont know if this works buy you could give it a try @fleet venture
there is literally no dragging code here though
sounds plausible to me
wait nvm
thats in the update i thought
ye it is
Are you using the input system pointer events or the mouse messages?
but tbh it seems like OnMouseUp would still get called even if it misses the Down
no idee
removing the mouse enter and exit does fix an issue
so its definetly better
but it doesnt fix the mouse up problem
well i checked it with Debug.log and its not getting called
yea i was just guessing.. as i havent ever relaly had code like this
and you only set dragging to true in MouseDown and Awake right?
theres always a down when theres an up lol
no i also call it here
public void AddObject(GameObject instance, bool isBackground)
{
gameManager.IncreaseObjectLayer();
var mousePosition = Camera.main?.ScreenToWorldPoint(Input.mousePosition);
if (mousePosition == null) return;
instance.transform.position = new Vector3(mousePosition.Value.x, mousePosition.Value.y, 0);
var prop = instance.GetComponent<Prop>();
prop.SetDragging();
}```
in SetDragging
i just set booth bools to true in there
i geuss i only need 1 bool now tho
I always use the event system drag events with a physics raycaster for things like this:
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/api/UnityEngine.EventSystems.IBeginDragHandler.html
that sounds quite complicated
same..
physics raycaster?
good stuff
Its not. you implement the begin drag, drag and end drag handlers, put a collider on your gameobject and add the physics raycaster to the event system
i just implement those and it works?
just keep in mind with this, UI elements can block your Raycasts
oh
as long as u have the raycaster component and an event system
so how do i fix that then
i mean
i want this object spawned above it anyways
wait thats not possible
š
is that possible?
isnt learning fun š
You can put camera mode to Screenspace camera and set certain plane so sprites can be above
do you just mean this event system?
Its good when you want say a UI button to be usable and not trigger drags for things "behind it"
yes that event system
By default, it only provides UI events
But it can also provide the same set of events for objects with colliders
Yea, adding the physics raycaster or physics 2d raycaster makes these events work with 3d and 2d colliders