#💻┃code-beginner
1 messages · Page 773 of 1
I detect british school/uni computer
indeed
currently my device has visual studio code and visual code, i want when i open resource it will go to visual studio code, what should i do?
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Follow the instruction above to configure ur vs code
yes, i have followed the instructions to configure it before
Did u set the script editor in the project setting?
settings, preferences, external tools, set to visual studio and restart unity
oh god i cant see visual studio code option
Browse and find it
Shouldnt be needed if vs code is installed correctly 🤔
thanks i found it,now just reboot right?
Good old “turning it off and on”, yes
thanks it worked there are some options of the app on the bottom right corner of the screen what should i do?
Whats the Quaternion.Angle equivalent for transform.position?
Reloading is fine. You can try the unity one by microsoft. Since it’s trusted it cant be that bad. Right?
Right?
There isn't, as position is not a rotation..?
thanks for the suggestion, i feel this unity version is quite good
U mean angle between 2 vectors? Vector3.Angle
There is no equivalent. Your question does not make sense.
similiar to this but just for position instead of angle
hold on
Position is a vector entity but it only represents a point. Vector in general means direction
which I use vectors so idk why I said position
wait I think I just figured it out
nope
im a dumbass
I don't know where the code is wrong but I don't have the "on collect effect" part like in the tutorial
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
and don't ignore the errors in your console
why is it ide, i remember doing it?
Lol it’s still not properly configured
Clearly something is missing
No wonder the vs code did not show up
The option is VS Code, don’t mistake it with Visual Studio
Hello, I am procedurally generating meshes at runtime. However, I want to use MeshLOD in the meshes I generate. Does anyone know how I can use its API?
Then you did't do it correctly.
The MeshLOD options are not visible in MeshRenderer. I think I need to generate a meshlod from somewhere in code
I followed the instructions in here, anyone having trouble with the ide?
easy fix
I have installed this extension, is this ide correct?
Hi guys. Since I couldn't find shader channel, I ll post it here. Is it possible to do 2022.3.62f1 URP shader that occludes everything behind a plane except skybox? I never did shaders and forums & otherwise havent helped much.... Found some which made ghosting, so the skybox would make artifacts...
Or really any other way to hide something from both sides, so its not visible in either direction behind a plane. Does not have to be a shader.
wouldn't everything behind a plane occlude anyway
or is this like some seethrough plane mask you mean that unrenders things behind it
Only objects behind it?
Yes
Yeah the use case is basically for a mod to a game where two side spawns shouldnt see each other for first X time.
so I thought about adding two planes in between and occluding everything but skybox/terrain etc
im new to unity but i cant find out how to makea door. I have watched a few videos and none of them have seemed to work, would anyone be able to help?
but the othe side needs to see the objects near them
hence why it must be invisible just for one side
and vice versa
This discord server* doesn't really like to discuss modding unless specifically about your project, but you'll probably want to look into stencils and using this transparent plane to update the stencil buffer
Doesnt stencil mean the materials on all the objs must be also adjusted?
it means all objects you want to cull must be a buffer value of +1 (where 0 is default)
meaning the plane updates the buffer from 0 to 1
plane must be in opaque queue too
rather the objects should be 0, if you made them 1 then it would be a reveal shader, but rather you increment it to 1 from the plane meaning all further pixels behind must be 1 or they wont render. I forget if this causes problems with the skybox though hmm
alternativley you can just write to depth but not draw... but I think this wouldn't draw the skybox either
if the stencil idea doesnt draw the skybox it means you should render the skybox twice for both buffer value 1 and 0
anyway, complicated stuff
Actually, I think this does exactly what I would want I think (I hope I can post links to official store here right? not affiliated with the author haha 😄 )
https://assetstore.unity.com/packages/vfx/shaders/stencil-urp-dh-shaders-288007
because this
it would take me ages to do probably 😄
Well, thank you for pointing me in the right direction!
if ive got a script that says
private Renderer renderer = null;
void Start()
{
renderer = GetComponent<Renderer>();
}``` does it matter if i leave renderer unassigned or assign it null?
im guessing it probably doesnt matter
that's fine
I would use awake though for when you're doing initial component referencing
for fields it makes no difference, if you include the = null or not, they are given a default value, which for a reference type is null
Renderer is a class, which is a reference object. All reference objects are assigned by default the null value when they are declared but not assigned. There are situations in which assigning null on declaration could be useful, but most of the time it does not matter.
Oh sweet summer child, search for "The Door Problem". Creating doors in games is weirdly one of the most complex things that you can do, due to the enormous amount of interactions that a door might have. Just do the minimal amount of logic possible for the door you need.
alr thanks
Valve put in lots of effort for the doors in HL a
Yep, doors in games work absolutely fine, as long as nothing is interacting with them, as soon as something does, chaos.
HL2/source engine doors are pretty decent till you break em too
DukeNukem 3D doors would sometimes insta kill you
if geometry moved, it most likely was able to kill you
There is a special door in half life 1 that gives you health!
just as a data entry error, its damage is set to a negative number iirc
Yea I think so but it's cool that it's even an issue. Speed runners make good use of it
but yeah one of the old projects i been on, and stupidly complex doors
does anyone know how to make a square hold an item and then have it rotate towards the mouse like in dani's video? the closest i can get is making the whole square rotate but not the item by itself
Ahhh... Just rotate the item's transform instead... Change the reference of the transform to the item's transform, simple as that
I tried that but it keeps rotating around the center of the item, instead of around the center of the parent square
Gimme code
sounds like the pivot for your sprite is wrong
the transform will always rotate around the pivot
where can you change the pivot of the sprite
sprite editor
the blue circle thing?
You can use the preset options or use a custom pivot
Having some issues with the player input. I keep pressing A/D but my character wont move. Any help?
Here's the controller code: https://paste.ofcode.org/8ziYrFBsqnj5NNkZ9HeTXT
You are mixing the old and new input system which is already a bad sign
can you also expand the Events to show you set those up correctly?
@crimson dirge ^
you mean these? Cause the context or whatever is related to it should be on the code
No this. You have it set to "Invoke UnityEvents" so you need to set those up here
Or change what Behaviour is
Uh oh.. is it possible the player's game object is missing...?
I believe this happened in the process of trying to replace the player script, which i might have failed due to this
then you can set this up again or change the behaviour mode. Please read the doc page linked above.
how can i make the animation not smooth?
Not an code problem, also i answered in #🏃┃animation
yah i know thx
HI, I'm using HDRP and I'm trying to make a throwing system but the balls don't stick to the walls
just added those debugs https://paste.ofcode.org/pEaknXeWfcf3xQ56rYsdH3 when I throw the ball towards a wall, it sometimes debugs " collided with something" and sometimes it does debug "collided with a wall"
instead just debug what the tag of the object is. theres no information to gain in the case of it working
the wall has the correct tag and there are no colliders interrupting the collision
Id really just assume its a problem with the collider, though cant see the outline in these videos. You could just use box colliders for this though instead of mesh colliders
I'll do it right now, great recommandation thanks
yes that's what I thought too, I don't really know a lot about rigidbodies but I thought it could be it too
it works with box collider @eternal needle thank you so much
weird that it wasn't working with the mesh collider
Maybe just a problem with the mesh. it being non convex couldve contributed but usually you wouldn't want to use a mesh collider if its not needed
i forgot where the PP layer is
this is a coding channel
oh yah
for real, now it never gets through the walls but sometimes it doesn't stick on it
InputActionMap with path 'UI' in asset "" could not be found. The Input System's runtime UI integration relies on certain required input action definitions, some of which are missing. This means some runtime UI input may not work correctly. See Input System Manual - UI Support for guidance on required actions for UI integration or see how to revert to defaults.
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
how to add UI to actionmap fast?
i cant play the game without add this?
Hey, Im starting to learn coding in unity and I was wonderign about this sample code:
Is tooltip a custom function, or a comment? It has information that would be more helpful for a programmer than a user, but i thought comments were made with //.
tooltips show up when you mouse over those fields in the inspector
so it's kind of like an engine comment yeah
is it some function defined in another script, or is it built into unity?
Both! It's a function defined in another script built into unity 😛
The syntax of [SomethingRather] above a class, function, field etc. is called an Attribute, It's a C# feature Unity uses in a couple places
In this case, When you select your WeaponController instance in the editor, when Unity runs its code to show you it's current values in the inspector it will look for those kinds of attributes and if they exist, use that data to best render those values for you
It's an Attribute. It's a thing that applies to a member of the class. In this case, Tooltip is a Unity-defined Attribute that puts text in the inspector when you hover over the variable. It's not a comment because it does have functional use, it's just that the function it provides is basically adding a comment to the inspector rather than the code.
alr, thank you !
Is there an easy way to check in my project, where a variable is referenced?
In visual studio you can right click the variable name and click find references
If it is a property, there is a small text that says references above it too
(if this feature is enabled in visual studio)
Most IDEs have a way to find references of some variable or type
and it will search my whole unity project?
Well it doesn't search your Unity project because we're talking about a variable, It just looks through all your project's scripts
Can someone help me? Why don't these red images scale properly with their parent object when I change the viewport size?
From my understand, I'm using the Vertical Layout Group and Content Size Fitter properly
the width and height are hardcoded
you need to enable the options for the layout group to control child width~~ and height~~
Doing that stretches them all the way to the edges
I just want them to be in the center
To look like this
At all viewport sizes
And when I add more, they'll stay in the center
thats too vague
how are the anchors set for the white box parent?
If you want padding on the left and right of the red elements then set the padding values on the layout group
The anshors on the parents are just at the edges
That means the white box and thus the red elements will resize width and height as the screen changes size
So I added the padding which helps with the horizontal space, but the vertical space gets weird at some sizes. And if I check "control child size" the boxes just disappear
when control width/height is OFF then the width and height set on each child rect transform is used
otherwise when control is enabled it will force expand width/height if enabled OR use settings from a layout element component
Thank you, I'll look into this layout element component
im still unsure what you want so best to just learn how it all works to do it yourself
I'm just having a hard time because every UI element I make scales correctly except these red boxes
Every time I change my window size, they change size
Only solution I can think of is to switch to a specific resolution
Its just because you miss understand whats happening rn. The parents anchors make the parent size change but the layout group children by default will just keep their width and height defined on their rect transforms
you can enable child width/height control and disable force expand so it will downsize when they would "stick out"
you can play around with it all in editor to see
guys when i start the game it makes me facing right even if i am mooving left this the code
void animationState()
{
if (movement.magnitude > 0.1f || movement.magnitude < -0.1f)
{
mooving = true;
}
else
{
mooving = false;
}
if (mooving)
{
anim.SetFloat("X", movement.x);
anim.SetFloat("Y", movement.y);
}
anim.SetBool("Moving", mooving);
if(movement.x < 0 && isFacingRight)
{
transform.localScale = new Vector3(-1, transform.localScale.y, transform.localScale.z);
isFacingRight = !isFacingRight;
}
else if(movement.x > 0 && !isFacingRight)
{
transform.localScale = new Vector3(1, transform.localScale.y , transform.localScale.z);
isFacingRight = !isFacingRight;
}
if(movement.y > 0 && !isFacingUp)
{
swordSP.sortingOrder = 0;
isFacingUp = !isFacingUp;
}
else if (movement.y < 0 && isFacingUp)
{
swordSP.sortingOrder = 2;
isFacingUp = !isFacingUp;
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I found a fix. In the canvas's canvas scaler, I set the UI scaler to "Scale with Screen Size" and set it to 1920x1080. Now the red boxes scale correctly no matter the viewport size
Aha thats what you meant, yes that is the best setting to use
Yea, seemed like I was doing everything wrong, but once I found this setting it just works
Not sure why it's not on by default, my god
idk why unity is yelling at me about object reference not set an instance of object.
for my player i have:
public static playerMovement instance;
//Update to player branch
private void Awake()
{
origSize = transform.localScale;
body = GetComponent<Rigidbody2D>();
boxCollider = GetComponent<BoxCollider2D>();
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this;
}
}
for my enemy base class i have:
protected virtual void Awake()
{
rb = GetComponent<Rigidbody2D>();
player = playerMovement.instance;
}
for my lizard enemy i have:
protected override void Update()
{
base.Update();
if (!isRecoiling)
{
transform.position = Vector2.MoveTowards(transform.position, new Vector2(player.transform.position.x, player.transform.position.y), speed * Time.deltaTime);
}
}
so like the player is a singleton, why is it not letting me access it
enemy base is mono behaviour, player is too. lizard inherits from enemy base
enemy awake probably is running before player awake
how would i fix that?
Stupidly simple question I'm just having a hard time finding the documentation for the UI Toolkit and style-sheets: how would I go about making my button-hover scale ONLY on the x axis? Like when I hover the mouse over it the button gets wider?
Oops- thank you! I shall scoot over there 
could move from awake to start
could manually make player earlier than everything else in Project Settings => Script Execution Order
could reference the singleton directly instead of caching it
could you help me with the 3rd option
how would i go about referencing it directly
not exactlhy sure what caching it means here
(you already do that when you cache it in awake)
caching is saving the reference for later so you don't have to do the work every time (if there is work to be done)
oh so i could just use playerMovement directly
still giving me an error
i honstly dont know how i got this error. what i did worked perfectly some time ago
can anyone help me with my player, base enemy, and enemy code? i cant seem to get my enemy to reference my player despite the player being declared as a singleton
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
where does unity load that list of dlls from when you try to add a precompiled reference to an assembly definition file?
Probably scans the asset database for them. Not sure it's serialized anywhere.
Could maybe run a project wide search in vs code or something
So when one is selected it just stores the name of the assembly with no path in the asmdef. I am trying to copy whatever dlls are selected to another folder with code but I cannot seem to find those dlls anywhere.
Does the editor store them anywhere when it builds the scripts?
Try opening the asmdef or it's metadata asset as text and have a look.
when you open the asmdef as text its just the assembly name without any path.
where does unity build the asmdefs out to any clue?
i bet i can find them there
The player and editor ones are probably in the library somewhere
Searching for one of the names in vs code or similar text editor tool, might find you a file that has the mapping of name to path.
But it could also be working on the basis of include paths, so the editor searches through the include paths for these names and doesn't have an explicit mapping anywhere. This is very common in build systems.
In Godot, Search Help and documentation was amazing. I could just look up what I wanted to do and it would explain clearly what something does, all the properties, functions, etc.
In Unity, I'm meant to use the Unity Documentation Website the same way, right? (and, is there a dark mode version?)
Yes, Unity has the Scripting API and manual documentation for help . . .
No dark mode that is native, use google chrome, open Chrome:flags or whatever the settings are called. Turn on experimental dark mode, and it will work using chrome for the HTML version, that is the only way around for it.
I can't enter play mode
Check the console error, debug the script
hey i have a bug
i dont know how it categorize
but whenever i have buttons and put an animator on it, it gets automically bigger
it says some name is wrong but i don't understand why
it says the name 'onCollectEffect' does not exist. did you create a variable with that exact name before trying to use it?
One isn't like the other (caseSensitive)
I already told him earlier 🤦
https://paste.ofcode.org/qXW2izVdvqCrDK3UMCsZAE Hi, if you could help me with this code, when I press R and the player gets out of the car, the player goes off the map. The player has ragdolls.
just one code with instructions but i made so many mistakes i am really frustrated
every error keeps happening
Hey y'all, I'm trying to make my variable set privately in only the same class but gettable in any class. so I thought solution would be to make a property? but it doesn't seem to work. here is an example.
public Bounds TestArea { get; private set; }
private void TestFunction()
{
TestArea.center = new Vector3(4, 0, 0);
}
I would like to edit the value of TestArea.center, but I cannot.
I have looked at the error message.
"Cannot modify the return value of 'GridManager.TestArea' because it is not a variable"
It seems odd but I guess I cannot change TestArea in parts (like one field in it), only all at once.
Here I have an alternative that seems to work to avoid this issue
public Bounds TestArea { get; private set; }
private void TestFunction()
{
Bounds newArea = TestArea;
newArea.center = new Vector3(4, 0, 0);
TestArea = newArea;
}
but I'm not a fan. I think I've found a solution to the issue but it feels messy and unnecessary. Is there something that just lets the first example work? or a nicer solution? I'm very new to properties so there's a lot I'm probably missing. I would just like advice or any suggestions of how to do this differently if possible.
I am aware of the alternative of making a private field and then getter methods to get them in other classes, but this is my attempt at an alternative to that because I don't like it much :p feels even messier tbh
this is the correct way for value-typed properties
god damnit
ok and what is a value-typed property?
give me a sec, there's a page explaining this that im trying to find
If its something you really want, you could just have a getter pointing to a regular variable
So a Bounds testArea;
And a public Bounds TestArea => testArea
Am too lazy to apply the formatting on mobile.
You just modify testArea in the script and other scripts get the value through TestArea
@astral void
there are 2 kinds of types in c#, value types and reference types. these effect how they're stored and how they're copied/referenced
you can look up those terms to learn more
by "value-typed property", i just mean a property that has a value type
ic o-o interesting
icic ty ^^
...that site looks very useful
bookmarking that ty
I think u should take a look at vs code tutorial and basic C# first to debug properly
heya agaain
how the hell do you add an inventory?
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
public class Inventory : MonoBehaviour
{
[Header("Gameobjects")]
[SerializeField] private RectTransform[] inventory;
[Space]
[Header("Positions")]
[SerializeField] private Vector2 slot1TargetPosition = new Vector2(-50, 50);
[SerializeField] private Vector2 slot2TargetPosition = new Vector2(40, 40);
[SerializeField] private Vector2 slot3TargetPosition = new Vector2(50, -50);
[SerializeField] private Vector2 slotStartPosition = new Vector2(-55, -55);
[Space]
[Header("Other Variables")]
[SerializeField] private float speed = 2500f;
[SerializeField] private bool isAnimating = false;
[SerializeField] private bool isOpened = false;
public void InventoryPosCheck(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Started && !isAnimating)
{
if (!isOpened)
{
StartCoroutine(MoveSlots(slot1TargetPosition, slot2TargetPosition, slot3TargetPosition));
isOpened = true;
}
else
{
StartCoroutine(MoveSlots(slotStartPosition, slotStartPosition, slotStartPosition));
isOpened = false;
}
}
}
IEnumerator MoveSlots(Vector2 targetPosition1, Vector2 targetPosition2, Vector2 targetPosition3)
{
isAnimating = true;
Vector2 endPosition1 = targetPosition1;
Vector2 endPosition2 = targetPosition2;
Vector2 endPosition3 = targetPosition3;
const float STOPPING_DISTANCE = 1.0f;
while (Vector2.Distance(inventory[0].anchoredPosition, endPosition1) > STOPPING_DISTANCE ||
Vector2.Distance(inventory[1].anchoredPosition, endPosition2) > STOPPING_DISTANCE ||
Vector2.Distance(inventory[2].anchoredPosition, endPosition3) > STOPPING_DISTANCE)
{
Vector2 slot1CurrentPosition = inventory[0].anchoredPosition;
Vector2 slot2CurrentPosition = inventory[1].anchoredPosition;
Vector2 slot3CurrentPosition = inventory[2].anchoredPosition;
slot1CurrentPosition = Vector2.MoveTowards(slot1CurrentPosition, endPosition1, speed * Time.deltaTime);
slot2CurrentPosition = Vector2.MoveTowards(slot2CurrentPosition, endPosition2, speed * Time.deltaTime);
slot3CurrentPosition = Vector2.MoveTowards(slot3CurrentPosition, endPosition3, speed * Time.deltaTime);
inventory[0].anchoredPosition = slot1CurrentPosition;
inventory[1].anchoredPosition = slot2CurrentPosition;
inventory[2].anchoredPosition = slot3CurrentPosition;
yield return null;
}
inventory[0].anchoredPosition = endPosition1;
inventory[1].anchoredPosition = endPosition2;
inventory[2].anchoredPosition = endPosition3;
isAnimating = false;
}
}
That alligns with my current script.
I genuinely do not know how to make an inventory script but I know it has something to do with scriptable objects
Well, an inventory is basically an array(list/dict) keeping track of your items data. Anything beyond that is extra.
oh alright
can you give me an example
like of code
private Item[] basicInventory;
touche
and Im guessing if I pick something up you delete the object and store the data in the dictionary?
Basically, yes. In the case above it's not a dict, but an array, though.
I cant think today alright
does anyone here maybe know why this https://paste.mod.gg/djicgzbjpclm/0 teleports the player to the wrong position?
I'm trying to make it just move the player to the empty game objects position on the other side of the map but clearly I'm stupid or something
it could be because the object is a parented object and there is an offset
hey guys
i have a problem
in this video are a lot of bugs
like there are 4 UI components one for health, one for the time one for cooldown fo the dash abilty and one of the score being the number of enemy killed
then the enemies, their bullets dont work as expected
then the buttons i have a button animation that when applied makes the button bigger than wanted
in other words this has a load of bugs
should i restart from zero or is this still savable ?
its important to learn how to salvage a project you think is broken
so how can i salvage it, its a burning pile of trash that if i change a singular line of script the whole game breaks
you're gonna be doing that a lot in any software engineering job
what's happening to the enemy bullets right now?
hi guys, i wanna make a sticking throwable knives and make them move with sticked objects. Currently using setParent but it make weird visuals when add my knife as child to not 1,1,1 object. Anyone can help me about that issue? Code: https://paste.mod.gg/rkywnqmbijnw/0
A tool for sharing your source code with the world!
but as a you can hear when the bullet spawns it stays in the enemy
When you spawn a bullet, I assume you're setting the velocity of the bullet to enemy's position minus the player's position. The concept is right, but you also need to consider that the enemy is moving.
Think of it this way; when you're running and throw a ball, the ball's speed = the speed you're running at + the speed that you throw the ball.
You need to set the bullet's velocity to the speed of the enemy + the speed of the bullet.
ok
but what about the UI
the buttons
or the fact that when i try to set up a game over system it doesnt work
How are you making the animation right now? What are you expecting from this button animation?
to get bigger when i put my mouse over it and smaller when i click it
Hmm what's wrong with the animation then?
the button size gets WAY bigger no matter what happens
maybe
i need to take a break
i already made two games this monthy
maybe in late december i will do it
hey i'm having a bit of a struggle with the unity input system: when unity reloads scripts at runtime it obviously resets all the references set in awake my question is: do i have to set the references that i set in Awake in OnEnable again - since something inside me tells me that this can't be how its being done - even tough it does work then. (and please ignore the unused method) https://pastebin.com/xEK9MSh3
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
make sure you only have one Instance
also you are assigning the object 2 times, in Awake and OnEnable
but isn't that the case here - only having one instance
it is, but you are not checking if Instance is null, otherwise you are overriding it
ur right but this did not rly answer my question - do i need to reset it when unity recompiles the scripts
i dont think that this is required
What the difference between polymorphism and interfaces? They seem very similar to me
!input ⬇️
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
you are using the Input class which is for the OLD input manager
oh fr so how does the new inputs work
Learn course: https://learn.unity.com/project/using-the-input-system-in-unity
Quick start from docs: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.16/manual/QuickStartGuide.html
did you try a unity restart
i tried and made a new project and the problem keeps showing
yeah just ignore it , it is a warning not an error on your side, seems like some internal bug
ik but my ocd cant ignore it🙂
urp
unity version?
umm, what would you do differently?
found nothing
i will try
Add>Ui Element>Image
wait what the actual mess did i concoct then
this looks rly bad then?
kind of you are mixing sprite renderer and ui elements
alright thank you
im gonna delete this
ty
hello i have this script here and it's very simple. it should on collision destroy the gameobject it collided with, if its called "player"
i have a collider on both the sphere and the "player" being collided
and the sphere has a rigibody
i launch the game and it when it collides nothing happens. no logs no nothing even
did you assign the Tag to the Player
do you have cooliders on both objects and at least one rigidbody
do i assign it by naming it in the hierarchy ?
yes
in the inspector of your player top right
you are welcome
i was genuienly smashing my head against the wall thinking i clearly must be stupid
nothing to worry about if you are new to unity
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i question why you want Start() to not be private automatically
unity monobehaviour messages should ideally be private so you dont call them externally
cuz the tutorial shows not private
Tutorials wrong then
Instead of following tutorial blindy, take a second to question the purpose of each step
plus idk why my character doesnt move too
heres my script for fp controller
and this is for player for now
Ignore it 😄
alr
Btw u can just remove the namespace keyword
ye just used to using it when im on c++
in school
so would it move like my character
and look
like the handling input i think is the problem
Are u using PlayerInput "Send Messages" mode?
nah any
I mean this
here is all my shit
Your callbacks have to be exactly like what the component generated for u
OnMove, OnLook
but where ?
Look at your code right now. You have onmove, for example
that's not correct
i dont habe any i think
You don't have any what?
onmove
yes you do
oh ok thx didnt see it for the first and second time
You should consider actually checking before saying you don't have something in your code
ye thx for the tip
if I wanted to make an airdash to not occur on the first few frames on a jump, would I have to turn my jump into a coroutine so that I can use WaitForSeconds ?
you wouldn't have to turn your jump into a coroutine but you might start a coroutine when you jump to wait the desired number of frames or probably better yet - the desired number of physics frames
Hmm okay Ill make a seperate one then and see what I can do
Tried something similar. Gotta say coroutine is way more complicated with physics steps
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Parts")]
public Rigidbody rb;
public Transform playerTransform;
public Transform camTransform;
[Header("Constants")]
public float movementSpeed = 100f;
public float jumpForce = 250f;
public float offset_x = 10f;
public float offset_y = 5f;
void FixedUpdate()
{
// Main movingness
rb.AddForce(0, 0, movementSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce * Time.deltaTime, 0);
}
var camPosition = camTransform.transform.position;
var playerPos = playerTransform.transform.position;
camPosition = new Vector3(playerPos.x + offset_x, playerPos.y += offset_y, 0);
}
}
``` My camera is still fixed to its original position and its not changing it to match the players with the offset why isnt it working
you're not moving the camera anywhere in this code
Just set the camTransform.position directly, no need to make a copy camPosition
All you're doing is modifying your local Vector3 variable camPosition
by the way, doing camera movement in FixedUpdate is a guaranteed way to make your game look "jittery"
well that makes sense im a bit of a dumbass sorry
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Parts")]
public Rigidbody rb;
public Transform playerTransform;
public Transform camTransform;
[Header("Constants")]
public float movementSpeed = 100f;
public float jumpForce = 250f;
public float offset_x = 10f;
public float offset_y = 5f;
void Update()
{
// Main movingness
rb.AddForce(0, 0, movementSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce * Time.deltaTime, 0);
}
var playerPos = playerTransform.transform.position;
camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
}
}
``` Ok so i tried to change it up a little it still dont work buh.
its been a long time from unity dont blame me
- Any errors in console?
- You shouldn't do physics in Update. Physics movement still goes in FixedUpdate. It's camera movement that needs to go in LateUpdate.
- Never multiply deltaTime into AddForce
- Are you using cinemachine?
no, ok, ok and no
And I'll jump ahead a bit here - you can't do Input.GetKeyDown in FixedUpdate either 😛
Realistically the camera stuff should move to an entirely different script
And the movement code is going to need to be broken up between Update and FixedUpdate with variables to share information between
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if (AmmoManager.Instance.ammoDisplay != null)
{
AmmoManager.Instance.ammoDisplay.text = $"{bulletsLeft / bulletsPerBurst}/{magazineSize/bulletsPerBurst}";
}
im following a tutorial so this may be a dumb question but its telling me the code does not contain a definition for "instance", however thats exactly what the guy the video did and it worked for him. can someone help?
Maybe show the console error
Onwhat line are oyu getting the error?
Assets\GunShoot.cs(80,25): error CS0117: 'AmmoManager' does not contain a definition for 'Instance'
Because in your code you have Instance here, but if there's an error talking about instance sounds like you miscapitalized it somewhere
Ok so open AmmoManager
ah ok ill check rq
you never defined Instance in AmmoManager
it may be a property too - just double check what the tutorial did in AmmoManager
i found what i did, i had two spaces in between the words AmmoManager and Instance, it works now thanks
White space doesn't matter. Likely misspelling.
Or the script hadn't been saved etc
why doesn't this print the mouse_pos O_O
is Button was clicked being logged?
oh wait no
well that would suggest OnClick() isn't called lol
didn't set it up apparently
why update the mouse world pos each frame?
or is this just testing. Looks like you are heading in the right direction
i am trying to create a draggable sprite when i click on the droplet button thingy. i have the sprite attached to the script, but problem is, OnClick() gets called only when i am pressing it once, i wanna be able to update the sprite image to my current mouse position until i stop clicking on it
like this
why not just use the event system interface if it's UI
Remember what i explained. you will need to respond to a drag event and spawn the real object and make it follow the cursor
ahh the dreaded ui system
the UI element should remain in place
i ain't changing the ui
i am only drawing a sprite at mouse position
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Parts")]
public Rigidbody rb;
public Transform playerTransform;
public Transform camTransform;
[Header("Constants")]
public float movementSpeed = 100f;
public float jumpForce = 250f;
public float offset_x = 10f;
public float offset_y = 5f;
// Main movingness
void FixedUpdate()
{
rb.AddForce(0, 0, movementSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce * Time.deltaTime, 0);
}
}
private void LateUpdate()
{
var playerPos = playerTransform.transform.position;
camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
}
}
``` I rewrote the code noesnt work still (the camera doesnt follow the player)
Just use cinemachine lol
No code needed
Great. You can use special interfaces to have your script be notified of UI pointer events: https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.EventSystems.IDragHandler.html
What doesn't work? You'll probably want to summarize if it's been a while.
You do not want a Button component to do this work
the camera doesnt follow the player at all. maybe it has to do with the offset or something?
Also should not use time.deltaTime in add force its already moved on fixed physics tick
why no button? Buttons are for a pointer down and then pointer up. You want a drag which is better handled with the events.
Likely not. Does the camera move at all? What about the player, does it move?
player moves, the camera doesnt.
Put a log in late update and see if anything prints to the console
okily dokily
Preferably the position of the player etc
If anything, you may have referenced the wrong object (a prefab perhaps)
nope everything fine with the prefabs
and the positions
Did anything print in the console?
Were the values correct?
what did you log and where?
also is there anything else that'd affect the camera position?
{
var playerPos = playerTransform.transform.position;
camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
Debug.Log("Camera position: " + camTransform.position);
Debug.Log("Player Position: " + playerPos);
}```
all of these should help
guys idk what to do after getting the movement down
anyway from your logs it's clear the camera is, in fact, moving
demn, camera into the stratosphere
the player is in the Andromeda galaxy
i should point out this is incorrect playerTransform.transform.position; should just be playerTransform.position; since playerTransform is already of the class transform
Hi, i just downloaded Unitiy. Has anyone a suggestion for a guide or a tutorial on how to code in Unity? And maybe an idea for a project which is simpel? (I have adhd so I need things that dont take too much time 🙁 )
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh lol thank you so much!
okilu dokily
dont ask.
not sure that would fix this though just bugged me
what should i do cuz i did this rn double jump and run and walk look around
im new to this
guys i am having problems implementing a delegate all over again...this
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class buttonScript : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[SerializeField] private Button button = null;
[SerializeField] GameObjectHolder objectHolder;
[SerializeField] spriteRender soritToRender;
Vector2 mouse_pos;
// Update is called once per frame
private void Start()
{
}
void Update()
{
mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
}
public void OnClick()
{
Debug.Log("Button was clicked.");
Debug.Log($"{mouse_pos.x}");
}
void OnDrag(PointerEventData eventData)
{
}
}```
You haven't listed the interface in your class declaration
You need:
public class buttonScript : MonoBehaviour, IDragHandler```
(P.S., the convention for class names is PascalCase, so ButtonScript)
Also there aren't really any delegates in this code
yeah, last time, i did not rly add any delegates but it somehow worked
convention is a stinker, it doesnt like when i capitalize every word in my variables (meaning including the first word)
There are no delegates involved here, so IDK what you mean by this. IDragHandler is an Interface
this is a different concept entirely
ahhh shiiii
So just for clarity, the camera's x and y values are properly updating whereas you've got its z value set to zero. The camera should be following the player relative to x and y unless... you're moving sometime else.
Idk man
The player moves perfectly
I checked its transform its fine
The camera dont move
At all
I think my codes autistic
Inside each log statement, after the string and variable concatenation, add a comma and the reference to each Transform.
The object is moving according to the logs. Concern would be if it's your actual camera. Another concern would be if you've got constraints with the camera.
how did you begin to understand delegates...you went through a process right? i just don't get it, it just doesn't click for me.
think of a delegate as just a variable that contains a function
i mean...i know that, but like, it doesn't make it intuitive enough for me to be able to use those functions
(You also might be combining the terms event,delegate and the concept of events together)
void MyFunction() {
Debug.Log("Hello");
}
void Example() {
Action a = MyFunction; // `a` is the delegate variable. The delegate type is "Action". We're storing MyFunction in it.
// now we can call it
a();
}```
delegates store functions, events are delegates which store functions which are called based on certain rules
void MyFunction() {
Debug.Log("Hello");
}
void AnotherFunction() {
Debug.Log("World");
}
void Example() {
Action a = MyFunction; // `a` is the delegate variable. The delegate type is "Action". We're storing MyFunction in it.
// You can also "add" them together:
a += AnotherFunction;
// Now it will run both:
a(); // prints Hello AND World
}```
The only thing special about an event is that it can only be invoked by the class that declared it
otherwise it's identical to all other delegates
there are no special rules about how it is called
oh wait
some code must simply invoke it
so like....a is basically a list which holds functions and when you call a, you call all the functions present inside a
yeah, sort of
just a delegate type - it means a function that returns void and has no parameters
or a modifier
delegate types describe the "shape" of the functions that can fit in the variable
Action is any function with void return type and no parameters.
So:
void Hello() {}```is an action but:
```cs
int Blah() { return 5; }``` is not
You can also do like Action<int> which would be any function that returns void and has a single int parameter'
e.g.
void Goober(int x) { print(x); }``` that would fit in `Action<int>`
aight, another question, how do you begin to decipher this? as in, for you guys, looking at this makes you understand exactly how you can use it, to me, it just seems to be unrelated stuff.
its an interface you need to implement. Its showing you the interface methods and what they will do
So first of all, the second screenshot is called an Interface, hence the naming convention of it starting with I
Are you familiar/comfortable with inheritance currently?
that i do know about, interfaces are basically classes which can be inherited multiple times
as in, you can only inherit one type, but you can inherit multiple interfaces
ok so you get how inheritence works with normal classes then
you can inherit the parent class's methods and stuff
interfaces are like a primitive version of inheritance where the Interface defines what the deriving thing will have, like a promise
then when some code has a reference to the interface (eg. IDragHandler), it can call those promised functions knowing whatever the interface actually is has some implementation of those promises
Interfaces exist because very different things can share similar behavior
here's a cursed example
public interface IPromiseToKillMyselfOnRequest
{
public void Die();
}
public class Car : IPromiseToKillMyselfOnRequest
{
public void Die()
{
Explode();
}
private void Explode()
{
}
}
public class Human : IPromiseToKillMyselfOnRequest
{
public void Die()
{
HaveHeartAttack();
}
private void HaveHeartAttack()
{
}
}
a Car and a Human are very different things, but both share the idea that they could "Die" in some shape or form
they have very different interpretations of what that means, as you can see
demn, it turned rly morbid all of a sudden
i've been up awhile forgive me
anyway, going off that
lets say we have this
public class WorldManager
{
public List<IPromiseToKillMyselfOnRequest> AllKillables = new List<IPromiseToKillMyselfOnRequest>();
public void KillEverything()
{
foreach (IPromiseToKillMyselfOnRequest killable in AllKillables)
killable.Die();
}
}
this WorldManager does not need to know if something is a Human or a Car or whatever, that's not it's job to know
but because of the promised Die() function in the interface, it can call that on all of them knowing that whatever has implemented that Interface, has provided some sort of answer for that function
so going back to your draghandler
hey i have a question if i have a big scene with many objects rendering in the scene. instead if i converted all the fbx files to stl and made a mesh reader and render all the object dynamically would that be better in term of memory or performance?
you would implement that interface (eg. class ButtonScript : MonoBehaviour, IDragHandler) and provide an answer to that promised function OnDrag() and whatever Unity has to manage the dragging systems will call that for you when it finds it
guys why i there is a big shadow following me
that's your shadow distance
shadows don't render past that distance
suppose i created something like this
public void OnDrag()
{
Debug.Log("Hoo");
}
does it get automatically called inside the void update() whenever i drag stuff, given that i have inherited the interface IDragHandler?
nothing gets called inside Update except what you write inside Update
It will get called by the game engine when you are dragging things.
not as part of Update though
Maybe you mean "every frame"?
so for every frame that i am dragging, it gets calles right
Update() is completely unrelated to this.
Unity has some way of finding all the things that implement IDragHandler that currently exist and will iterate through them and call that function when relevant
It will get called on every frame in which you move the mouse while holding it
and it does so outside of the update()?
update or frame
for every frame that i am dragging
technically all that stuff happens in your EventSystem's Update
you can see this in the profiler
At most I think every frame yeah, but as mentioned in that doc every time the cursor is moved so on frames where you haven't moved the cursor and are still dragging it won't fire
Worth pointing out just in case that the frequency of when the OnDrag function is based just on how that specific interface was implemented in Unity, nothing fundamentally with interfaces as a concept defines when they will be called
it's an actual mystery the fact that unity can call the correct stuff inside every update method available across all the scripts in the right order
Once you get more comfortable with Unity you'll be even more weirded out with how Update, Start, Awake work etc.
it's certainly not standard / "good" practice
Also there is no "right" order btw, it just depends on how your code is setup for if it will or will not be affected by a "bad" order
i finished my double jump mechanic but when i double jump and then go a bit down i can double jump again what should i do to fix it
got it working, now what is the difference between this and what the drag handler is doing?
why doesn't it call onComplete() by itself
this is a longer answer so i'm gonna raincheck that for a sec
well how does the double jump work, ie share the code
should i send my scripts for movement
how about give it to me later cus i am pretty ded tired
i woke up at 11pm and it's 8am now 😭
time passes too fast 😔
thx for helping though
@gus_fring__ muted
Reason: Sending too many attachments.
Duration: 29 minutes and 54 seconds
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
for that first one though, they are both two different ways of achieving the same outcome yeah.
This is a super rough "idea" of what Unity is doing but with the interfaces Unity might be doing something like
private void EventHandler : MonoBehaviour
{
private List<IDragHandler> activeDragHandlers; //They collect these using some kinda magic dw about it
private Vector2 lastMousePos;
private void Update()
{
//They might even use some event from the new input system stuff instead of this update check
if (Mouse.current.position != lastMousePos)
{
lastMousePos = Mouse.current.position;
foreach (IDragHandler handler in activeDragHandlers)
handler.OnDrag()
}
}
for later.
https://paste.ofcode.org/d3PmZAcQMdUKTiHnptqx3c In the coroutine I set up so that I can airdash but I noticed that when I airdash I angle ever so slightly downwards so Im assuming that gravity is having some influence over my airdash when Im trying to go exactly straight
You have to disable the rigidbody's gravity for the duration
set gravity scale to 0 at the start of the coroutine and reset it to normal at the end
isnt gravityscale a unity 2d thing?
there's a bool for 3D
useGravity or something
it's on the Rigidbody
Unrelated but StopCoroutine(AirDash()); doesn't do anything. You have to save the reference to the coroutine when starting it and then use the reference to stop it
I was just gonna mention that haha
Oh okay I made multiple changes when I added that and assumed that was the reason
that made my airdash work
It's a bit of a mess, that made it "work" only because it didn't stop the coroutine immediately
Can someone help me understand why I keep getting an "Unauthorized" log when it comes to this function
[CloudCodeFunction("SavePlayerData")]
public async void SavePlayerData(
IExecutionContext context,
IGameApiClient gameApiClient
) {
try {
await gameApiClient.CloudSaveData.SetProtectedItemBatchAsync(
context,
context.AccessToken,
context.ProjectId,
context.PlayerId!,
new SetItemBatchBody(new List<SetItemBody> {
new SetItemBody("test", 1),
new SetItemBody("test2", 2),
new SetItemBody("test3", 3),
new SetItemBody("test4", 4)
})
);
}
catch (ApiException e) {
_logger.LogError($"Failed to save PlayerData: {e.Message}");
}
}
Unauthorized means you tried to take an action you aren't authorized to take
presumably you tried to save data to a project id or player id that you don't have permissions for
or maybe the access token itself is bad
Could it have something to do with the fact that I'm testing it in play mode? So I'm signing in anonymously and could not have a player id?
Because the function is on CloudCode, it should have access to everything
Now would be a good time to start debugging
print your access token, project id, and player id
all are not-null
are they even nullable types? It's not about if they're null
it's if they're valid and sensical
Yeah they're valid, I probably shouldnt send a ss of them right?
The server is clearly telling you that you're not authorized to do what you're trying to do
see if there is any other data in the exception
there should be a message
this is all it says
what api is this
The GameAPIClient, just following the docs https://docs.unity.com/ugs/en-us/manual/cloud-save/manual/tutorials/cloud-code
every one of those examples is using context.serviceToken
you're using accessToken
is that the issue?
I would certainly expect an unauthorized error if you're using the wrong token
Some use AccessToken some use ServiceToken apparently, I guess I can try with service token
https://services.docs.unity.com/cloud-save/#tag/Data/operation/setPrivateItem
Looks like you need a service account token for this endpoint
This looks like important info about the two types of auth tokens: https://services.docs.unity.com/docs/authentication/
can someone give me tips to start coding in unity?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Can smbd pls help
tysm
Hey does unity not support .NET 5? For some reason I can't use IReadOnlySet even though it was added in .NET 5.
only these supported: .NET Standard 2.1 .NET Framework 4.x
I used last dot net version on my server when I need .NET latest support and just communicate from game with server
how to fix this shaking in the walls???
It happens when you fight physics putting something inside colliders outside of FixedUpdate frames. Also this is a code channel. If you have a question about code, post code.
Any one have advice how i might make make an object "float" around a sphere (a planet)
Im made a prototype using physics to "attract" the player to a specific radius around a planet and it work but breaks if you move too fast,
Are there other ways i could acheive this effect? like attaching to player to an empty game object and rotating it around the planet maybe?
are you looking for physically correct orbital mechanics, or are you looking to just rotate an object around another?
is there a way to call StartCoroutine in an abstract class? I'm seeing a lot of "no" and it ruins stuff ;-; basically I'm trying to run a function in a class that inherits from an abstract class, polymorphism stuff, and in that function i want to call a bunch of coroutines. I'm thinking I could switch to an interface instead of polymorphism and that might fix it but hoping for other solutions
There's nothing special about starting a coroutine from an abstract class vs anywhere else
just note that StartCoroutine is a method on MonoBehaviour, so you, as always, need a reference to a MonoBehaviour instance to call it on
yes... but i get "An object reference is required for the non-static field, method, or property" error
public abstract class ActionClass
{
public abstract void Activate();
}
public class NewAction : ActionClass
{
public override void Activate()
{
MonoBehaviour.StartCoroutine(MatchManager.instance.ChangePhaseVisualRpc("phaseName"));
}
}
example code, error here
yes, as always you need an obejct reference to call StartCoroutine on
oh I read your message wrong oops
You can't just call MonoBehaviour.StartCoroutoine
you need an actual instance to call it on
yeah...
it's not a static method
StartCoroutine(MatchManager.instance.ChangePhaseVisualRpc("phaseName"));
This is a code smell
is there a reason you don't just start the coroutine right there?
MatchManager.instance.StartChangingPhase("phaseName"):
because i want to yield return it (forgot to put that in oops)
then on MatchManager:
public void StartChangingPhase(string phase) {
StartCoroutine(ChangePhaseVisualRpc(phase));
}```
no, look
this is how you should do it^
and call this
MatchManager.instance.StartChangingPhase("phaseName");
I want to run a few coroutines and have them happen in order, I don't know how to do that with your method
ok lemme edit it to better show what I mean
MatchManager is a MonoBehaviour, right?
your issue is not that this class is abstract, your issue is that this class is not a MonoBehaviour
just FYI
public abstract class ActionClass
{
public abstract IEnumerator Activate();
}
public class NewAction : ActionClass
{
public override IEnumerator Activate()
{
yield return StartCoroutine(FirstRoutine());
yield return StartCoroutine(SecondRoutine());
yield return StartCoroutine(ThirdRoutine());
//function that called Activate will now continue their own code since this has finished
}
}
this is more what I'm trying to do, I hope it's clear enough-
yeah ty
Yes it's very clear, but you need a MonoBehaviour to run coroutines
So - you need to create a dedicated monobehaviour for running the coroutines
and run them on that component
That could be your MatchManager if you want
or some other singleton
A big part of the ActionClass though is that it is called from MatchManager and then MatchManager waits for the coroutines to end... not sure how to make the code wait for the functions to end in that case... is there a way to pause a function like that?
Ok so like I asked before, is MatchManager a MonoBehaviour?
oh yes sorry
but I need to know when the coroutines are finished-
private IEnumerator ChangeAction()
{
yield return StartCoroutine(ActionOrder[CurrentActionIndex].Activate(new PhaseActionParams()));
CurrentActionIndex++;
CurrentActionIndex %= ActionOrder.Count;
}
the code is incomplete and I plan to change this, but currently this is what I have
this is in MatchManager
Ok so looks like you're already doing it in a coroutine
so there should be no issue
but Activate certainly needs to return IEnumerator for this to work
not void
like you had in this example
Instead of:
yield return StartCoroutine(FirstRoutine());```
You can just do:
```cs
yield return FirstRoutine();```
it works the same
so it won't move then until the coroutines in MatchManager is done?
that's what yield return does
oh i didn't know that
if you really needed to call StartCoroutine, you can always do MatchManager.Instance.StartCoroutine(...);
but it's not needed here
No not correct orbital mechanics , more like a precise "float" around the planet
You move forward and you maintain a desired radius around the planet and curve around it.
Rn im applying a force to move forward (local forward because the player could "upside down", then im applying a force that gets bigger the further you are away from the target radius)
float is kinda vague to me
Perhaps like, hovering around a mario galaxy planet? It's tougher to do with Rigidbody
oh I was wondering if that was possible but... it sound so messy 😭 yours sounds better
anyway, I'll get back to you on if it works or not later
Basically that yes. but instead of walking around a planet, i want to float or more accurately "hover" around it.
Imagine an "invisible ground" that my player walks on that is 10 units away from the surface itself.
I want to do it with a rigidbody because my game is expected to have many collisions.
but if its way easier to do without im all ears
2 questions. 1. is this efficient? 2. How would I be able to discern an actual string and a JSON serialized string?
public static async Task ModifyPlayerData<T>(
IExecutionContext context,
IGameApiClient gameApiClient,
string key,
Func<T?, T> modifier
) {
string playerId = context.PlayerId!;
try {
var result = await gameApiClient.CloudSaveData.GetProtectedItemsAsync(
context,
context.AccessToken,
context.ProjectId,
playerId,
new List<string> {key}
);
T? currentData = default(T);
if (result.Data.Results.Count > 0) {
object value = result.Data.Results.First().Value;
if (value is string stringValue) {
currentData = JsonSerializer.Deserialize<T>(stringValue);
} else {
currentData = (T) value;
}
}
T newData = modifier(currentData);
await gameApiClient.CloudSaveData.SetProtectedItemAsync(
context,
context.ServiceToken,
context.ProjectId,
playerId,
new SetItemBody(key, newData!)
);
}
catch (ApiException e) {
_logger.LogError($"Failed to modify PlayerData: {e.Message}");
}
}
what do you mean by "an actual string"?
Ok let me ask a different question actually, now that I read this a little
Why are you not sure if the data you're getting back is a json string or... something else?
are you expecting both things to come back?
Because CloudSave will serialize all objects on save, when getting, if the value can be deserialized into a .NET object, it will auto do that, otherwise it stays as a JSON serialized string
Why would the value ever not be able to be deserialized
If it's not able to deserialize it, you can probably just give up, and spit out an error, no?
Presumably you should know the actual data type you expect to come back you call this I would think
Well if I ever had like a custom class/type that I wanted to be saved, it would be JSON serialized on save, but would not be auto deserialized on get
would you ever be saving a raw string that wasn't json?
I mean, currently idk, I'm just still setting up the foundation before I dig into actual player data
I would like the option to be available if it ever arose. Maybe like DisplayName, that could be a string
For any given key, you will know ahead of time the type of data or will be
It's a non issue
true, maybe I can just have the Function deal with deserializing and return object, so when saving back it will just serialize
I kinda hate that the api is trying to serialize/deserialize for you
Well it has to serialize from what I understand, like you cant just store actual objects. It's like compression.
I did however change my code
public static async Task ModifyPlayerData<T>(
IExecutionContext context,
IGameApiClient gameApiClient,
string key,
Func<T?, dynamic> modifier
) {
await ModifyPlayerData<T>(context, gameApiClient, key, modifier, false);
}
public static async Task ModifyPlayerData<T>(
IExecutionContext context,
IGameApiClient gameApiClient,
string key,
Func<T?, dynamic> modifier,
bool deserialize
) {
string playerId = context.PlayerId!;
try {
T? currentData = await GetPlayerData<T>(context, gameApiClient, key, deserialize);
var newData = modifier(currentData);
await SavePlayerData(context, gameApiClient, key, newData);
}
catch (ApiException e) {
_logger.LogError($"Failed to modify PlayerData: {e.Message}");
}
}
a normal api would just take a string for example
json
and expect you to serialize it yourself
that's what I mean
ohhh
or even a byte[]
Did unity remove go language?
Unity uses C#
i meaaan...
Unity has never had anything to do with Go
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Parts")]
public Rigidbody rb;
public Transform playerTransform;
public Transform camTransform;
[Header("Constants")]
public float movementSpeed = 100f;
public float jumpForce = 250f;
public float offset_x = 10f;
public float offset_y = 5f;
// Main movingness
void FixedUpdate()
{
rb.AddForce(0, 0, movementSpeed);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce, 0);
}
}
private void LateUpdate()
{
var playerPos = playerTransform.transform.position;
camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
Debug.Log("Camera position: " + camTransform.position);
Debug.Log("Player Position: " + playerPos);
}
}
``` Im trying to make the camera follow the player but it isnt working.the player is moving but the camera isnt can somebody help me with this its been a while since i was a dev on unity twin
do you have any scripts on your camera
maybe somethig is prevent it from moving
and make sure you dont have any errors shown up in the console
nvm i fixed it i was updating the x axis when it was going in the z axis
I think I've seen you here for a few days now. You might want to provide the screenshots that you've last had or a link to the latest discoveries. Last I recall, your coordinates were being updated (although extremely high in value) but supposedly the object (camera) wasn't moving. Either it's referring to a different object (main camera etc) or you've got some constraint that prohibits the camera from moving (physics constraint, Character Controller component, code or something other)
no ive fixed it its fine and this is my second day now
dj giggle nuts signing off for now
#📲┃ui-ux , is your canvas set to screen space overlay
wait what
never mind the debug is working, you said it is not working, i can see the debug log
only one of the debug logs is working, the rest, onclick and ondrag end aren't working
yeah ok. it must be the mouse Position
mouse_pos = Mouse.current.position.ReadValue();
ScreenToWorldPoint expects a vector3
Just to be clear, if you want the end drag function to occur as well, you'll need to interface it.
class A: B, Drag, DragEnd, etc```
yep that too
IEndDragHandler
you might want to check this doc : https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IDragHandler.html
i did check it out, nothing seems to work though
You can find all of the event handlers on the left side of the documentation site
do what i said and it will work, change the line with mous_pos
what the hell this worked
So you'd just append a comma and the above to have the function implemented be used.
asdfsfashdfsdhfuiuasdguoiyhuryn
i hate images, i downright hate them i absolutely disgust them
public void OnClick()
{
Debug.Log("Mouse Clicked.");
}
public void OnDrag(PointerEventData eventData)
{
if (!ImageToRender.enabled) ImageToRender.enabled = true;
ImageToRender.transform.position = mouse_pos;
Debug.Log("Mouse being dragged.");
}
public void OnEndDrag(PointerEventData eventData)
{
Instantiate(GameObjectHolder, mouse_pos, GameObjectHolder.transform.rotation);
ImageToRender.enabled = false;
Debug.Log("Mouse stopped dragging.");
}```
this is how my code is now
show the whole script. we need to see if you are implementing the Interfaces
i am
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour, IDragHandler, IEndDragHandler
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[SerializeField] private Button button;
[SerializeField] GameObject GameObjectHolder;
[SerializeField] Image ImageToRender;
Vector3 mouse_pos;
// Update is called once per frame
void Update()
{
mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
}
public void OnClick()
{
Debug.Log("Mouse Clicked.");
}
public void OnDrag(PointerEventData eventData)
{
if (!ImageToRender.enabled) ImageToRender.enabled = true;
ImageToRender.transform.position = mouse_pos;
Debug.Log("Mouse being dragged.");
}
public void OnEndDrag(PointerEventData eventData)
{
Instantiate(GameObjectHolder, mouse_pos, GameObjectHolder.transform.rotation);
ImageToRender.enabled = false;
Debug.Log("Mouse stopped dragging.");
}
}
ondrag and onendrag did shwo on the debug log, onclick too, if i click it...
What kind of object is a droplet?
Clones are being spawned but they aren't visible for some reason
change the rotation to Quaternion.identity instead GameObjectHolder.transform.rotation
that pretty weird too, they are present on the same layer as the rest of the units
wait
Perhaps they're behind the other images (if they're visible and actually present at the location)
wait, my recorder isn't working, i can show you that that isn't the case
You could quickly verify by clicking on a cloned object in the hierarchy and checking it's position, rotation etc
exactly
you need to learn debug techniques and analysing problems, this will save you alot of headache
Were those values acceptable? (note that they're all low and negative values)
why would they show up the right way on the scene but not the right way in game
here's the thing, before this, i have been using sprite renderers to make images, not the button image component. now i find myself in the position where i know how to layer images using heirarchy and hwo to layer sprites using sorting layer. those values aren't goin to make sense cus those are the sprites...
oh wait
wait then why does it show up in scene O_O
i don't understand, if its below the cavas, it shouldn't show it
The scene view isn't necessary from the camera's view.
Either way, check those values and see if they're acceptable
i am assuming something is wrong with your camera, did you change any settings there
nah, they are what they used to be
ignore the mousescript, it's what i was using before to do this
Show us the inspector and components of the visible droplet. How does it differ from those not visible?
they all have different z components
Here's the inspector for the non visible btw
Can you show us the image?
So manually try changing the z value for a non visible cloned object and see if it becomes visible.
this is my mouse position's z component
ya well, it becomes visible
my mouse position's z component is under the whole thing probably
So maybe you ought to edit that value before using it to instantiate your clones or use a edited vector 3 copy of position etc
thing is, i should not be using magic numbers is what i have been told, so i don't think assigning it a fixed z value is the right way to do it
You do understand that converting mouse pointer from screen to world disregards the z component
the z component in that case is supposed to be the thing which is present highest at the heirarchy, which in this case is the main camera. the z component of that is supposed to be my mouse's z component when i do screen to world
i need a fix for it...
if you really want to use it you need to give it a z value manually
I tried, good luck.
don't wanna do that cus of this
but i see that as a work around and i woudl not recomend it. instead fix the sorting layers etc
The z component is a throw away value when converting from screen to world space as it's generally right where the camera is. We'd use https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Camera.ScreenPointToRay.html in 3d as it accounts for z (not applicable for your case - don't bother)
so i should just hardcode it then?
Sorting layers would resolve a lot as they would not be conflicting with shared priorities
Try 0
that works
I'm certain you are not the first and that this is perfectly viable.
just for clarification, when would you consider hardcoding something to not be a malpractice
may i ask why you are using ui lement to drag and drop but then instantiate a sprite
Random ambiguous values that may need to be changed. In your case, you're only working with 2d and presumably everything relative to z should be at 0 where you would then have to use properly sorting order (other than the camera that's default to -10 which is where your z values would normally be when converting from screen to world point)
the sprite being instantiated has an animator attached to it, the ui element works great while i am draggin it, but once i instantiate the object, i intend to start its animation too
but you can do that with ui lements too
but it's not ui, as in, the object instantiated ain't a part of ui right
could you clarify or elaborate what you are trying to say?
you can use animations on ui elements too

is a tower considered ui O_O
or is ui basically any interactable object on screen
good question.
what's the answer O_O
i´d probably use a sprite
Truthfully, it may have been too close to the camera and culled as that point should have been where the camera was (literally on the screen with regards to z and not some distance away, where your sprites were)
ya, that is exactly what was happening
the image isn't getting displayed somehow...while it is being dragged
public void OnDrag(PointerEventData eventData)
{
if (!ImageToRender.enabled) ImageToRender.enabled = true;
ImageToRender.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
Debug.Log("Mouse being dragged.");
Debug.Log($"{mouse_pos.z}");
}
public void OnEndDrag(PointerEventData eventData)
{
GameObject GameObjectToSpawn = Instantiate(GameObjectHolder, new Vector3(mouse_pos.x, mouse_pos.y, 0), Quaternion.identity);
ImageToRender.enabled = false;
GameObjectToSpawn.SetActive(true);
Animator anim_temp = GameObjectToSpawn.GetComponent<Animator>();
anim_temp.enabled = true;
Debug.Log("Mouse stopped dragging.");
}```
Has to do with whatever image to render is (and likely with it's position or enabled state)
does ImageToRender have a sprite set
its not a sprite, its an image
this is the image being held
no, it's just one sprite
is that what's assigned as the ImageToRender?
"set" as in the verb, not the collection/group lol
droplet_notarget_0 is a sprite there, it's set to the source image field there.
oh lol
yes, it is a sprite being referenced by the image component which in turn is being referenced by the script
Anyone who could teach me an easy way to implements states for a player?
well, given that it's a UI element, it generally shouldn't be moved via position iirc? but anchoredPosition of the RectTransform instead
Can you show more of the script?
also how are you setting mouse_pos
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour, IDragHandler, IEndDragHandler
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[SerializeField] private Button button;
[SerializeField] GameObject GameObjectHolder;
[SerializeField] Image ImageToRender;
Vector3 mouse_pos;
// Update is called once per frame
void Update()
{
mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
}
public void OnClick()
{
Debug.Log("Mouse Clicked.");
}
public void OnDrag(PointerEventData eventData)
{
if (!ImageToRender.enabled) ImageToRender.enabled = true;
ImageToRender.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
Debug.Log("Mouse being dragged.");
Debug.Log($"{mouse_pos.z}");
}
public void OnEndDrag(PointerEventData eventData)
{
GameObject GameObjectToSpawn = Instantiate(GameObjectHolder, new Vector3(mouse_pos.x, mouse_pos.y, 0), Quaternion.identity);
ImageToRender.enabled = false;
GameObjectToSpawn.SetActive(true);
Animator anim_temp = GameObjectToSpawn.GetComponent<Animator>();
anim_temp.enabled = true;
Debug.Log("Mouse stopped dragging.");
}
}
umm wot
i know world space means the scene coordinate system, whereas local space is the relative position of an object to another object, so...local space uses an object as its origin
there is another
O_o
two more, actually.
there's screen space and viewport space too, which are both relative to the plane of the screen
one is in pixels and the other is normalized, i don't remember which, probably screen space in pixels
what mode is the canvas set to?
you should be able to choose between screenspace overlay/camera and worldspace
world space
is it scaled?
in the transform, shouldve been more specific
alright, so that all checks out (though tbh, having it as a non-UI object would probably be easier, and then you could keep the canvas in screenspace)
have you checked the position of that preview image at runtime at all
i don't know what to look at, it doesn't rly show up on the hierarchy....should i debug log it?
this stuff shows up in the inspector, not the hierarchy
select the preview image, look at its position, see if that changes as expected when you move stuff
if it does, it might just be layered incorrectly
if it isn't, it might be this
Lets say I made a simple little error when initially setting up my project and might have created a 2D project instead of a 3D project. Is it possible to convert it somehow?
it basically just affects the default packages installed and the default scene template/scene view setup
if you change all of them to how they'd be in 3d (installing the 3d feature, removing the 2d feature, etc) you could "convert" it
but it's not really anything intrinsic to the project
Yeah makes sense, I noticed that e.g. its using a 2d renderer etc.
if you aren't super familiar with unity yet and you haven't done much work, it'd probably be easier to just make a new 3d project and copy your work over
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Parts")]
public CharacterController CharCont;
public Transform playerTransform;
public Transform camTransform;
public Transform GroundCheck;
public LayerMask ground;
[Header("Constants")]
public float movementSpeed = 100f;
public float jumpHeight = 250f;
public float offset_x = 10f;
public float offset_y = 5f;
public const float GRAVITY = -9.81f;
public float sphereRadius = 0.5f;
private bool isGrounded = true;
void FixedUpdate()
{
var velocity = Vector3.zero;
isGrounded = Physics.CheckSphere(GroundCheck.position, sphereRadius, ground);
velocity.z += movementSpeed * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
var target_velocity = Mathf.Sqrt(2 * jumpHeight * GRAVITY);
velocity.y = target_velocity;
}
velocity.y += GRAVITY * Time.deltaTime;
CharCont.Move(velocity);
}
private void LateUpdate()
{
var playerPos = playerTransform.transform.position;
camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y += offset_y, playerPos.z);
}
}
``` Ive decided to use a character controller instead of a rigid body and i am horrible at physics but can somebody tell me how to fix this?
CharacterController uses Update, not FixedUpdate
okilt dokily
aside from that self-evident issue, can't really answer much
you haven't said what issue you have to fix lol
it does
just btw, CC does provide its own isGrounded if you apply a constant gravity
so i havent tested the game with the update function but the ground check doesnt work and the player is jittery when it touches the groud
how?
oh, it wasn't in the hierarchy because it doesn't exist lmao
you're modifying props of the prefab, not an actual gameobject in the scene
ya...that's what i said
so.. why didn't you figure out that it wasn't showing up in the scene because it's not in the scene
that's pretty straightforward
so i assign the prefab to a null object and then reference it?
CharCont.isGrounded
i knew it wasn't in the scene, so when you asked me to check for the image, that's why i replied by saying i don't rly know what to look for...cus it actually doesn't show up on the hierarchy...
that's not really what i was asking
then i prolly misunderstood
right here, from your initial question
the image isn't displayed because it doesn't exist
the hierarchy is the list of things in the scene
if it's not there, it's not in the scene
so what do i do then...create a empty object, attach a script to it, which references this prefab and then reference that script ?
no, you instantiate the prefab by dragging it into the scene
you probably don't even need the prefab, this would be a single object
no, you don't need to reference the prefab at all
you aren't instantiating it at runtime
oh wait a sec then
Just have it in the scene somewhere and hide it till you need it via enable/disable the image component. Reference that instance.
prefabs are gameobjects turned into assets, that can be referenced and reused
right now you need a gameobject actually in the scene
you didn't put it in the canvas
Rect Transform usually indicates that they are part of a canvas
oh ya, i do remember someone telling me to not just yank it outta the canvas
Order may matter btw
@ivory bobcat @naive pawn @frail hawk thx for all the help guys
now that i can instantialise the droplet onto the screen, i wanna know how you guys would recommend me to pick and drag those objects...should i use rays or smth else
glad you were able to fix it
i also wanna know how you might go about erasing them cus the dragon in the corner, that's a gameobject with an animator component, what i wanna do is basically, if anyone wants to sell a deploye dobject, they should be able to pick it up, then drop it in front of the dragon and then the dragon animation plays and the object gets destroyed
oh rob i finally implemented what you told me to use
sounds like you should step back and plan that, in terms of design
it should be pretty straightforward to implement, but you gotta figure out the logic flow to go about it
You can actually make use of the same event system that UGUI uses! Meaning the same pointer event interfaces.
You just need to use 2d colliders to the objects and add a "Physics 2D Raycaster" to your camera
last time i tried doing something, i planned to use sprites and whatnot...and guess what, it was the wrong way to go about things
is it..?
ya, i used sprite renderers on ui instead of image
oh, yeah, that's a mistake
spriterenderers aren't
the mistake is spriterenderer + canvas
it's either spriterenderer on its own, or canvas+image
but i did mention before, that having the preview and actual placed objects be non-ui objects would probably be easier tbh
just the UI things should be UI
just so i understand it right, you mean to say that movable objects should be non ui whereas unmovable ones should use ui image component ya?
im not basing it off of moving or not moving
here we go again
i'm basing it off of what is actually UI
UI should be UI
nonUI should be nonUI
that's all im saying
no
no
O_O
Anything interacting with the scene would probably not be ui.
Look at any other game, you KNOW what is user interface and what is not
UI would be like data input, controller or whatnot
pause menu? User interface
health text? user interface
unit on the ground? gameplay sprite/model
sometimes things mix but knowing when to use one solution over another is important
the things in red here are UI. the placement/range preview could be considered UI, but it'd be easier to treat it as not
These are ui
ahh shii i am colourblind
ah shit. what color would be better
use black
