#💻┃code-beginner
1 messages · Page 529 of 1
ok so THATS what serialize field means
honestly i was confused on why its was a string
ok this is my new code so the parenthesis is the field that i can change in the inspector and the other value is the default?
until you change it in the inspector
WAIT i think i just had an aha moment one sec
you still need to do this
#💻┃code-beginner message
in general, making a behaviour tree system
ur right sorry got aheasdf of myself brb
i just want to point out, if you want to use a behavior tree you no longer need to write your own or use a third party asset. unity has its own behavior tree package now called Behavior
i did all that before i started but its giving me this error
it says the unity extension is installed and i did all the other steps on there
you need to install the .net sdk. helpfully there is a convenient button to click to get it
this one?
well that will be a tool that will install it
is that what appeared when you clicked the Get the SDK button? 🤔
yeah i see it now, but the popup went away, i'm really sorry i rlly should have just looked.
scroll up in the output console and there will be a link to download it there too
its not there
it tells you you need to restart in order for donet tool to be recognized in PATH
have you restarted your pc? the extension seems to think it was installed but just isn't in the path
anyone know where I can find an expert in ML-Agents (or Unity in general?) I guess they don't allow job posting on the server but if someone could get me in the right direction I would appreciate it
#1202574086115557446 oh if you are lookin for collaboration then we do not do that here
hello i have question , create GameManager Script and have one problem. script dont create gearwheel and i cant move this in inspector slot.
I guess it might be a better place however its dead
!collab would be your best bet for collaboration
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I know
is it monobehaviour ? also the gear icon thing has been patched. You no longer get one
but perhaps does someone know someone who I could contact outside the server
for AI in particular? you could contact the local google search to find someone
other than that I do not think anyone knows anyone in particular, so the link I sent above would be your best bet
ok thanks
i mean some people here would probably be who im looking for but they don't allow job posting here right
correct they do not allow job posting here, you can do that here though #💻┃code-beginner message
it doesn't change anymore in gearwheel ?
nope
ooook, but why i cant move script to Inspector ?
you either. Have compile errors or the script is not a MonoBehaviour
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
trigger this script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
but am getting a nullreference exception
what gives?
second link is blank
my bad
needplacement manager
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Selector_Script.current is null
because you are accessing it before it has been assigned. you should really look up how to set up a singleton correctly so you don't run into these issues where you try to access it before its even been assigned
make sure you initialize anything, including a singleton in Awake
everything else that use those use Start
these singleton objects also do nothing at all to ensure that only one of them ever exists at a time
check out https://unity.huh.how/references/singletons for a good example of doing that ^
this is two test script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hi, how do I set the position of a transform relative to another without them being parented to one another please ? I'd basically like to put one object on top of the other, so Vector3.zero in the local space of the other object
you cannot have two MB in one file, same with Scriptable object
unity doesn't like that
Alright, i put the reference to the selector_script in awake and it seemed to work, correct me if i'm wrong but essentially what happened was that PlacementManager was trying to get the Selector_Script before that reference even existed, right?
either assign them to the same transform.position or use something like a ParentConstraint
yes, which is exactly what i told you here: #💻┃code-beginner message
put each of your classes in a separate script file . . .
no, these are two separate files, I just put the code here together
this is giving me a good old connection timed out
I thought singletons were simply scripts you only use once, or in a single gameobject
rlly? thats strange working fine here, I believe its hosted on github so if github loads it should work
singleton = only one *should * exists
i can access github just fine
I was going to say there's a way to do it using transform methods, because changing parents can cause issues, and I found it : calling TransformPoint(Vector3.zero) on the non-moving object will return the world space position needed. Thanks for answering !
a singleton only ever exists once. there can only be one. if a duplicate is created, either that or the original is destroyed to ensure only one exists at a time . . .
multipleton
that is literally the same as doing transform.position = otherTransform.position
Science deemed it impossible, yet here we are
no those are just instances lol
... yeah you got me there lmao
it's mostly a learning moment, wanted to learn to make an editor extension.
Camera Dragging Issue in Unity
I am using the NavMeshAgent from the unity tutorial to get pathing from A -> B in a 3D space. Everything seems to work fine with this. However, I created a script and I have to attach the NavMeshAgent to a variable in the script. I do this with:
void Start ()
{
this.agent = GetComponent<NavMeshAgent>();
}
If I do this and press 'Play', Unity crashes and I have to ctrl+alt+delete end Unity... Anyone knows whats up?
hey guys, sorry for interrupting, but i have a question
don't apologize, just ask away . . .
this code would not cause a crash. you likely have an infinite loop somewhere in your code
so i have this code for my animations, its a top-down rpg kind of game, and it does work, but that many if statements might lag the game in the long run and its just annoying to look at, is there a way i could simplify it?
Is there a way to go through the code line by line?
yes, you can use the debugger and break all when it freezes. then inspecting what the main thread is doing will show you where your infinite loop is
yes, breakpoints
Because it seems that I have no infinite loops. It also crashes when I add this component to the public variable during runtime.
show the entire class
you could use Horizontal and Vertical Inputs.. and then feed them to an animator with a blend
so something like: *** if (v > 0 ) {etc} ***
if statements would not lag, the difference is literally so miniscule modern pcs are not affected
for game, you should be more worried about renderers and assets lagging your project before anything else..
It's a bit messy though, not really refactored yet. If I comment out the part in the Start() method, it doesn't crash. It crashes when I invoke Start(). An instance of the Inhabitant is created by the CreatureManager (also included)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use a paste site instead of posting directly in chat. mobile users can't see the code . . .
first function works, second one doesn't pop up in on click field
public fields are already serialized btw, you dont need SerializeField
this is not what i meant when i said you can reuse the component btw
oh well lol
usew buildindex instead of strings
that local variable is useless
dear god that site is ass. can you use one of the sites the bot linked
sorry i got confused, but it was easier and made more sense to me to change the string value within the function instead of in the inspector
the whole point is to have each one of these with a diff scene name
you're creating a local SceneLoad string in each of your methods. they are not assigning the SceneLoad class variable . . .
that doesnt make the script modular.
not everytime you want to add an entry/method for that scene you have modify the file
instead of having 1 file that serves multiple purposes
Haha, I'm sorry. https://paste.ofcode.org/CpPGKkHjWB66KwSjCwLFHd
There it is... The second class is in the bottom
so ur saying i can use the same function toi load different scenes?
public void LoadSomething(string sceneName)
{ Load sceneName }
you need a method where you can feed in the scene name
public Animator animator;
private float horizontal;
private float vertical;
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
animator.SetFloat("Horizontal", horizontal);
animator.SetFloat("Vertical", vertical);
}```
soemething like this
two variables between -1 and 1 passed to the animator.. it'll use those to blend between the 4 different animation types
well you've got a while loop in update which is typically a bad idea because it can lead to infinite loops if the condition never changes
ohmyy
Not ideal, still needs to be refactored.If I don't do this.agent = GetComponent<NavMeshAgent>(); on line 43, it just says empty object on line 85.
I always put a while loop in Coroutine another good way it dont hang the Update loop
again, that isn't what is causing the infinite loop. however if you don't assign that variable the infinite loop can't happen on account of a NullReferenceException on a previous line
what is likely happening is that you are instantiating the object within 5 units of a tree, which means on its first Update, it enters that infinite loop. and because you aren't incrementing its resourcesGathered variable (i assume since you've not shown the StartCuttingTree method), the loop never ends
you're also relying on strings for the states which is . . . not great. and your if statements are all separate making it possible to cycle through multiple states all within a single frame
ok last attempt i filled in the field as "MainMenu" which is my scene name but the functionm is not showing up in the on click event space
Mhh, let me spawn my inhabitant somewhere far
did you add the scene to your build settings?
show what the OnClick shows
i bet you dragged the script from the project folder and not the instance
yes
then we need to see how you setup the OnClick button from the inspector . . .
I gotta come clean. It was an infinite loop. Exactly like you described with the cutting tree. Thank you all so much for helping me out!
yes you put the wrong script
you need to drag the Instance thats on a gameobject
nice. was trying to find this link but wasnt sure wat to search lol
you have to drag the GameObject that has the script attached to it in the field, not the actual script (from the project folder) . . .
ok cool
What is the best most Memory Efficient way to get a Camera's (which isnt rendering to a RenderTexture) Image in sprite format?
^ ur fillin the variables of an instance of the script (gameobject w/ script attached).. not the actual script
probably copying the buffer to a texture then make sprite from texture
thank you so much it wasa driving me insane
OH now i get why its because the public string is attached to thye game object
its because each Instance has their own version of the string with different values
every time you attach a script to a gameobject a new instance is created of that script, each has their own version of the data
awesome thank you so much sorry that was so frustrating I'm working on paying more attention to things and problem solving
takes time, and also experience which comes with time so all you need is time and patience to learn
ya, dont be sorry bout wanting to learn :D... 🍀
theres the total opposite types of ppl that come in here..
Hi, I need to to update a TMP_Text in a Task.Run (because i do some others async operation there) but when I do so the text isn't updated in Unity, even if it is in the inspector
I tried to use ForceMeshUpdate(true); but it didn't change anything
Would anyone have any advice on that?
Task.Run schedules the task to run on the threadpool which means it may not run on the main thread. you cannot use the majority of the unity api off of the main thread so that won't work
i unsure if that runs/works on the main thread. if not, then it won't update . . .
Is there any other way to call async function for Unity?
use coroutines . . .
you can call async just fine, they are referring to another thread, something different
Just run them normally, not in Task.Run
you can call async methods without running them on other threads. or use a coroutine, or Awaitable on unity 6
are you not using async/await?
If I do so they would freeze my game wouldn't they?
Only if you are doing I/O or a lot of work in a single frame
I tried to use a Awaitable but the method is called when I click on a button and Unity told me the method had the wrong return type
call the async thing from the button listener
I'm using a library so yeah it might do lot of things, I'm using a TMP_Text to keep progress on that
btw in the new Awaitable class you can switch to the main thread for specific functions to run within that Task
programming is all about indirection/layers of abstraction. Use them
"using a library" is meaningless
Be specific
what are you doing
Sorry I didn't get that message
I'm using an external library that have a method such as "ConnectAsync"
So in my settings when i click to the connect button the text keep track on when it's connected
public void OnButtonClicked() => SomeAsyncMethod();
private async void SomeAsyncMethod()
{
//whatever
}
I'll try that
async function will not block the thread, no
if it's truly async
Wow indeed it worked thanks, looks like i need to review my C# basics
how do I clamp the camera from looking to far left and right? my character is stuck in a chair for my game so I need to lock how far they can look left and right but I'm only finding stuff about clamping the y axis on google
exactly the same way you do it for the Y axis
so change y axis to x axis and lock it (75, 0, -75)?
BTW looking left and right generally is rotation around the y axis.
so would I change which cords I clamps? I'm confused now
Change compared with what?
You'd need to explain what existing thing you're talking about
I have the y axis clamped so the player can't look to far up or down, so would I run another code like that one but change the order of the cords I'm changing?
x is up and down
man this changes everything I knew about coordinates( tbh my only knowledge was from minecraft)
Think about it as rotating around an axis. Left to right rotates around the Y axis. Up and down rotates around the X axis.
up down.. like u got a skewer thru the X
left right.. like u got a skewer thru the Y
🍢
would I need to create something for the camera to pivot from or can I just clamp the camera it's self?
you clamp a float only to pass to camera x
I make camera child of empty so I can create recoil without affecting cam
the easiest way to achieve this is to use cinemachine which can allow you to enable/disable the rotation clamping at will super easily
are you using unity 6?
that's just the scene view. they also just have some of the overlays on the left instead of docked on the top
i just stack them all together on the left
I'll look into it!
the way i've always done look/cam controllers
is to have 1 gameobject rotate only left and right, with the camera nested beneath that would go up and down..
this is the simplest way i've found.. and helps combat gimbal lock..
- OuterContainer < left-right
- InnerContainer < up-down
cinemachine is also a good choice, as mentioned by box
im new att scripting/programing in Unity and i dont know if this is a problem or not but in others code i have seen this "using System.Collections; using System.Collections.Generic; using UnityEngine;" but i can only have "using UnityEngine;" in my code. is that a problem or am i overthinking?
okay
would a statemachine be appropriate for handling UI? To ensure that players can't bring up the inventory while they're in the pause menu and things like that. Or is there a better way to handle this that I'm unfamiliar with?
Sure. State machine would be appropriate.
To understand what using does:
With using:
using UnityEngine;
public class MyClass : MonoBehaviour {
}```
Without `using`:
```cs
public class MyClass : UnityEngine.MonoBehaviour {
}```
That's the only thing using XXX does - it lets you write the short names for types without the full namespace.
Hi! I'm working on a jigsaw puzzle and I can't figure out why my remainingPieces variable doesn't count down correctly. It only ever decreases by 1 no matter what pieces are placed. Can anyone look over this and help me? This is just the function it is in but I can share more of the code if needed.
Well, you're doing number - 1, so of course it would only decrease by one. I don't understand what the issue is?
I need it to iterate everytime a piece is placed
sorry, to keep decreasing every time another piece is placed
Does it not?
How are you verifying that its not working correctly?
Are you printing out remainingPieces somewhere
in game mode, I can see the value of remainingPieces.
And it goes down by 1 each time? Or only really ever does it once? meaning from 12 -> 11 and thats it
it only every goes from to 11 no matter how many pieces are placed
Is the logic running more than once? If it isn't it means that your logic isnt being entered
Your conditionals are false except for once
And do you see the Subtracted one log printing in the console for each piece?
If you don't see the print every time you get rid of a piece, my guess is it has to do with the Name conditional
Yeah, these conditions do look very suspicious.
Honestly I don't really get the logic behind them.
yes i see the "subtracted one" more than once
I was following a tutorial
I can send more of the code if that will help
Can you put a debug log and just verify its not counting down. Put it right below the line of code remainingPieces -= 1
i'm gonna go ahead and guess we are looking at logs from different objects. or you've omitted some other important code
This is not a very long script. I can send if that will help
sure. but just to confirm, these logs are all coming from the same gameobject, right?
Different. This script is on all the picture pieces because that's what the tutorial did😢
well that would be why then. each instance of this component has its own remainingPieces variable that is entirely separate from the other instances
I'm not sure how I should split up the script so all the pieces can move and remainingPieces will be calculated
separate the logic out. have one central object that keeps track of all of the pieces, and have each piece tell that managing object when it's been used/placed/filled/whatever
I'm new to referencing c# scripts in other scripts so can you please help me how to divide this out : (
give this info a read for getting references to other objects: https://unity.huh.how/references
Either make it static meaning it would belong to the class and not the instances (not advisable), or make some manager object that keeps track of this and not the pieces keeping track of it.
making it static would mean they can't assign to it in the inspector
so keeping all the code that allows the object to move and check it's placement in one script, how would each piece report to a manager script that it is correct and subtract from total remaining pieces
by getting a reference to that manager object and calling a method or decrementing a variable or by raising an event that the manager object subscribes to
ohhh okay. so instead of referencing the movePiece script in the manager script I should reference the manager script in the movePiece script?

The cleaner way would be to have the manager script get a reference to each piece. Each piece could fire off an event when its 'collected'? or killed or whatever happens when your piece is subtracted. The manager subscribes to (listens for) this event and subtracts from the total number of pieces in response to the event in its own function.
😢
Whats there to be sad about lol?
I'm just so lost on how to do this
Do you have a manager script yet?
I just made it so it's empty rn
I'll give you a high level overview.
- Have a manager script get a reference to all the pieces.
- Stick them in a list for now.
- Use loops to achieve this. While looping, subscribe to an event that the piece script will fire off at some point.
hi i have a question i use rig builder.build in update to update two bone ik constraint in every fps and when arms gets to the target goes like crazy theres any solution to that?
In the piece script you could, at the top of the script, declare an action like so,
public event Action PieceSelected;
I have never used an event like that😶
Its ok, its a powerful tool and pretty simple to use
I can walk you through it pretty quickly
let me know if you want to, or if you create it or whatever
I'm cutting and pasting the code that handles the win state and remainingPieces and this is the code I have for checking if a piece is in it's correct place. If I can use this, how can I then send to the manager script to subtract ?
So this is code on the piece script?
yes
Ok so in here you would fire off the event if you created it already
PieceSelected?.Invoke();
how would i do an event in here☹️
Where you want to subtract from the total amount
just put that piece of code I just pasted. Did you create the action earlier when i typed it from above?
yes I did
Ok so just do the invoke somewhere inside that if statement
cool.
Ok thats all from inside the piece script. Just to clarify. You created an Action event. And wrote code where and when it should fire off.
Now into the manager script
do you have any references yet at all to the pieces from inside the manager script?
So, no I don't think I have references to them. The movePiece script is just attached to every puzzle piece
Gotcha ok. Where is the manager script located inside the game?
This is everything in my move piece script
I can attach it to my game manager
Do the pieces have some common GameObject parent?
no but I can make one
Theres many ways to get references to GameObjects and Components. We will do simple for now.
How bout in the Piece manager script, you create a serializedField List to store the pieces in and then show me its made
unity can serialize ints just fine
I mean preferably I would make it the class that is your Pieces
like if your pieces are Piece then the list could be List<Piece> pieces;
The word piece just looks wrong now. I've read it too much.
in this manager script i only have an int for remainingPieces
Thats fine, did you create the list?
the list should not be int
Its not going to be a list of ints
Its going to be a list of the pieces
What did you name your script for your pieces?
ohh okay thank you
yupp
got it fixed
Cool. Ok. Now open the editor. Go click on the GameObject with your manager script on it.
You should see the serialized empty list.
You can select and drag all the piece GameObjects into this list I believe
You may need to lock the inspector so it doesn't switch while you are trying to drag and drop
Which you can find there
got the list filled in
Coolio. Now lets create a private void OnEnable() method in the manager script as well
Does your project match the tutorial 1 to 1? Because if you followed a tutorial, it should work. Did they have that script on each piece in the tutorial as well?
yes
created
Have you used loops yet?
no, just if statements
Ok. Lets create a simple foreach loop. It simply loops over each thing in the list.
Then you missed something in the tutorial.
foreach (var piece in Pieces){}
in OnEnable() correct?
Yupp
👍
Ok. inside the loop we are just going to subscribe (listen for) the events that each piece has.
piece.EventActionName += SubtractFromTotalPieces
replace EventActionName with the name that you gave the event in the Piece scripts
SubtractFromTotalPieces is just a name I came up with. This is going to be the name of the method you need to make that will contain the code that will subtract from the remainingPieces
Thats.....it, really. There is some good practices to do as well but lets see if this works first.
Thank you so much
Thank me when its over lol
I created the subtractFromTotalPieces func
Awesome, it needs to be exact name of the func minus the ( ) in the foreach loop part
test it out if you have the code that subtract from remaining pieces already written
I just cut this from the movePiece script
cool, give it a rip
infographic I made for you
This is essentially what we did
Use these tools every day and you will fly and better understand them as you go. Continue to make lists, loops, events!
This error randomly showed up out of nowhere and I can't figure out how to fix it
when I double click it, the inspector seems to bring me to a file called "Graph"
Driving me wild
Try resetting the windows layout. It seems to be a random ui error in one of the windows/tabs. Probably in something using graphs, like an animator controller or shader graph.
Clear the console and see if the error appears again.
Oh I just restarted it and it fixed itself lol
Lowkey was freaking me out
Check the stack trace in the console. It'll tell you what line the error is on. If it's not in any scripts you wrote, it's probably a unity thing (particularly if it has an address hash instead of a line number) and can usually be resolved by a restart
Thanks!
Restarting worked
Anyone have ideas on why I'm getting this error?
FishGenerator:
https://pastebin.com/HbvbHN37
FishingPool:
https://pastebin.com/ehqbDFGM
Json File:
https://pastebin.com/eLP5hXzU
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.
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.
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.
For some extra context, I'm attempting to generate a fish with random things chosen from the JSON file so it's not hard coded variables.
But I am having issues trying to get it to override the FishingPool using the Unity JSON utility
Yeah I'm kinda genuinely at a loss because from everything I can find, I did it right?
Try creating some JSON using the API and comparing it against the JSON you're trying to load
After trying that and just attemping to load the same json without doing anything to it I still get the same error.
It also looks like the formatting is the same?
For reference this is what it generated
Look at what you're doing with your function and its return type
hello everyone, does anyone know why this says type mismatch once i assign it?
void GenerateAndAssignNoiseTextures()
{
// Generate shape noise (Texture2D)
Texture2D shapeNoise = GeneratePerlinNoise(resolution, shapeNoiseScale);
effectScript.cloudSettings.CloudNoiseTexure = shapeNoise;
// Generate detail noise (Texture3D)
Texture3D detailNoise = ConvertToTexture3D(GeneratePerlinNoise(resolution, detailNoiseScale));
effectScript.detailCloudSettings.DetailCloudNoiseTexure = detailNoise;
// Generate weather map (Texture2D)
Texture2D weatherMap = GeneratePerlinNoise(resolution, shapeNoiseScale * 0.5f);
effectScript.cloudSettings.WeatherMap = weatherMap;
}
all of the variable types are correct
What do you mean by assigning this?
when i set the variable equal to something
You'd have to show us the other code here
like this:
effectScript.cloudSettings.CloudNoiseTexure = shapeNoise;
its a scriptablerendererfeature, so unless theres something really simple and dumb or there are restrictions on scriptablerendererfeatures im not sure why it doesnt work
Is this an editor script or runtime
runtime
the type mismatch error comes up during runtime
so i added this debug log at the end:
// Generate textures
Texture2D shapeNoise = GeneratePerlinNoise(resolution, shapeNoiseScale);
effectScript.cloudSettings.CloudNoiseTexture = shapeNoise;
Texture3D detailNoise = ConvertToTexture3D(GeneratePerlinNoise(resolution, detailNoiseScale));
effectScript.detailCloudSettings.DetailCloudNoiseTexure = detailNoise;
Texture2D weatherMap = GeneratePerlinNoise(resolution, shapeNoiseScale * 0.5f);
effectScript.cloudSettings.WeatherMap = weatherMap;
Debug.Log("Textures assigned to Effect script in editor.");
and its printing it without any errors in the console but it still says type mismatch
Share the actual error
And it's details
You said there's a type mismatch error
And cloud noise texture actual type?
I remember there being a similar issue depending on how you create the texture.
im getting null reference exception but i can't figure out whats wrong
im following the 2d beginners whatever
aparently the problem is line 18
you dont have those variables
dumb it down for me
you need an isPressed boolean, and im assuming keyboard, current, and the arrow keys are part of unity's new input system
unless the tutorial says otherwise
this code was copied and pasted from unity's own tutorial
i think unity is stroking out
Is your project configured to use the new input system ?
should be?
It’s a yes or no question.
Edit > Project Settings > Player, make sure Active Input Handling is "New Input System" or "both"
How do i enable nullable in csproj without unity overwriting it everytime i renegerate project file ? I'm tired of adding # nullable enable on every file
Put this on the top of your files:
#nullable enable
Sorry i confused enabled with disabled, edited my comment
yeah i'm tired of writing that every single time
Alternatively you might be able to add a Directory.Build.props file next to your sln or csproj file. You have to add this to it:
<Project>
<PropertyGroup>
<Nullable>enabled</Nullable>
</PropertyGroup>
</Project>
Not sure if Unity supports this but modern .NET does
Try it and seeeeeeeeeeeeeeeeee
I saw that answer on stackoverflow but one comment said it is ignored in unity 2022, havent tried myself though
Let me try i guess, txn
Yeah otherwise you're out of luck (probably)
Unity works on updating its codebase to modern .NET in which case it's probably enabled by default
Um it is disabled by default, hence why im tired writing nullable enable
I know that, I mean that future .NET versions have it enabled by default
Not the current one
ooh i didnt know, txn
hey guys
im new to this game thing
can anyone help me, im making pvz through a tutorial on youtube but i cant seem to get it right
theres a bug in my game and im completely lost
i have an rectTransform object with height set to canvas height but it's higher. y?
!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
im trying to drag the sunflower to the game field but when i do that it came looking like this at it changes it scale scale whenever i try to hold and drag my mouse, any idea what causes this. im already using rigibody2d and made it kinetic
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ObjectCard : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
{
public GameObject object_Drag;
public GameObject object_Game;
public Canvas canvas;
private GameObject objectDragInstance;
public void OnDrag(PointerEventData eventData)
{
objectDragInstance.transform.localScale = Input.mousePosition;
}
public void OnPointerDown(PointerEventData eventData)
{
objectDragInstance = Instantiate(object_Drag, canvas.transform);
objectDragInstance.transform.localScale = Input.mousePosition;
}
public void OnPointerUp(PointerEventData eventData)
{
throw new System.NotImplementedException();
}
}
this is the code
you are changing the localscale via mouse position
thanks 😄
Try using localPosition instead
Hey guys, I have just started out with unity
And I'm trying to make an FPS game
However, when I go around with the youtube tutorials
It ask me to use CharacterController.IsGrounded to check whether it is grounded or not
But it seems unreliable as sometimes the isgrounded will be false even though the character is already touching the ground
Why is that??
Hey guys, I need help again, I dont know why when i placed my sunflower on the container it becomes so small, theres a comparison between when im dragging on the container. heres the code for the PlaceObject function implemented in GameManager
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject draggingObject;
public GameObject currentContainer;
public static GameManager instance;
public void Awake()
{
instance = this;
}
public void PlaceObject()
{
if (draggingObject != null && currentContainer != null)
{
Instantiate(draggingObject.GetComponent<ObjectDragging>().card.object_Game, currentContainer.transform);
currentContainer.GetComponent<ObjectContainer>().isFull = true;
}
}
}
Any ideas as why its like that?
this is the code for objectContainer
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class ObjectContainer : MonoBehaviour
{
public bool isFull;
public GameManager gameManager;
public Image backgroundImage;
public void Start()
{
gameManager = GameManager.instance;
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (gameManager.draggingObject != null && isFull == false)
{
gameManager.currentContainer = this.gameObject;
backgroundImage.enabled = true;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
gameManager.currentContainer = null;
backgroundImage.enabled = false;
}
}
am I missing something?
should i re adjust the height and weight when its dropped?
You're instantiating it as a child of the container
Presumably the container has been scaled
Child objects inherit the scale of their parents
It would be best if the container object is not scaled so you don't have to worry about it
Oh okay, where do i change that?
https://hatebin.com/ldlzyavtnh https://hastebin.com/share/pixidoraye.csharp
hello I have these scripts but the vinewhipframes are replaced by the scratchimageframes Idk why like when I use vine whip the scratch animation played instead
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
u meant this scale right?
and i should make the scale of the container 0 0 0 ?
1,1,1 not 0 lol
i am so lost, i changed the width and the height but its still so big
after i changed the scale to 1 1 1 😅
any idea on how to make it smaller?
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
private Rigidbody2D test;
[SerializeField] private float jumpForce = 10f;
void Start()
{
test = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if () {
Input.GetKeyDown(KeyCode.Space);
}
}
}
Ok im currently learning C# dont laugh abt my code 💀
Invalid expression term ')'
what do they mean with this error
im no expert but i think its ur if statement
i dont think u could left it blank like that
yea it was if statement
i fixed it
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
test.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
hehe bit stupid of me
Configure your !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
We already told you this yesterday
There is no point in helping you with such basic issues, especially when your editor would do that if you actually configure it
this was not the question
xD
i never said i had issues with the ide
It doesn't matter what the question is
not until u config ur IDE..
i mean you can but they'll go unanswered
so that is not the question or problem
How about you read my messages instead of assuming these things?
i already had my IDE configured XD
If you configured your editor it would inform you of the issue, and where the issue is
Show a screenshot of your editor
you can do the same with me i said i didn't have issues with the IDE
read this xd
Then you need to learn to read your code better because your editor would be very clear where it finds issues
yea but i asked what the problem is
well doesnt really matter all that much
hope yall have a great day
im going to develop further 😄
well learn xd
God bless yall
Great, next time you should learn to read the code because your editor has a nice red squiggly line underneath places where there is an issue. Just like in this screenshot
Yeah idk how they could not notice this
Bold of me to assume it's a misconfigured editor 🤷♂️
no clue, just giving a demonstration for what it i should look like..
i asked what the problem with the error was XD i gave the erorr
i said what does this error mean
idk why you guys keep talking further if the problem is finished 😆
no worries tho XD someone else said the same thing in #💻┃unity-talk so i prob typed smth wrong english is not my primary language so was prob a problem on my end XD
thank you btw didn't even knew this somehow 💀 hehe
you guys tried to help me that is kind 😄
this is a code channel
do anyone know how to code so when i look with my player only the upper body rotate and not my legs. i have legs and upper body as different gameobjects.
- root
- upper body
- camera
- lower body
- upper body
then just rotate the transform of upper body
oh ok thx
How do I make a ball rotate on the surface ? Do I use transform.rotate or is there a better way ?
transform.rotate would make it just spin in place..
would need a rigidbody and something like rb.AddTorque i would guess
hello guys, does anyone know how do i make an endless 2d background?
parallax bg is the terminology i think ur lookin for
i mean, like a endless jetpack joyride BG
not using a paralaxx BG, cuz im trying the 2D basic one
tks
ohhh thats relatively easy. https://www.youtube.com/watch?v=lWCMhpGuyrU&ab_channel=HerbsterGames something like this?
check the outro and see if thats what you mean?
is it appliable to 19:6 res?
with a bit of critical thinking yes
🍀 best of luck
okay so if I make
bool flag = variable > 0
it's set in stone that it's true if variable is more than one the moment it called?
it's not a "pointer" to that equation and I would need to make a method for that, right?
just double checking
not a pointer... no just a regular operation
same as 1 + 1
the > operator is just like any other
bool variables cannot hold "pointers"
I just had a wild assumption for some reason
you might be confusing things with expression-bodied properties>?
You could make a property like bool flag => variable > 0;
maybe
makes sense
That's basically equivalent to:
bool GetFlag() {
return variable > 0;
}```
yeah, I recall how properties works
however I am pretty blind to those => thingies
people tend to use that so called sugar oftenly and I am just getting confused there usually
its "basically" just a shorthand for a function
not litterally, theres a lot of different stuff happening under the hood, but as an end-user it works almost the same on the higher level
This concept is called imperative. C# is an imperative language, meaning each statement is a change in the program's state. Other languages can be declarative, where flag = variable > 0 would declare a dynamic variable which is true whenever variable is greater than zero.
yeah normally the property is:
bool Flag {
get {
return variable > 0;
}
}```
Shorthand way is:
```cs
bool Flag => variable > 0;```
Also if you want the "pointer" way you described, look at UniRx / R3 and their ReactiveProperty
is that any different from making a usual property?
You can't store a property in a variable, unless you store it as a method reference. Reactive libraries store these properties in objects that can easily be passed around.
oh, right
How is that different from a delegate?
less annoying to use I would assume?
delegates are super easy!
yeah, but that might be faster to use
anyway I don't need neither at the moment, I am just curious
I misremembered how reactive libraries work. They are reactive, as in you can't access the value on demand like a delegate. They represent streams of data that you can observe and react to.
are arrow functions => lambda expressions or are they something else completely?
I have never used them before and they are probably great for short functions
It depends on the context. The same symbol is used for two different things, lambda expressions and expression bodies.
I hate seeing it in other people's code ><
Nice to know at least that it's not just lambda expressions
I mean wise versa...
I was always assuming it's a lambda expressions and it's too hard for me to comprehend
I mean, because it's troubling for me to understand, not because I hate them for using them
ah, so expression bodies are basically just short functions, Although I would have to look into the documentation more to learn how to use them properly
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members
How can I find out that the "model" objects in my picture are actually children of an fbx file and not the fbx file itself? Because if I get the AssetPath for these gameobject it returns the .fbx path, but that's different
I am validating these objects so I need to reliably skip the prefab and fbx and only look at the objects with the empty icon
can you even change the base fbx you exported?
I would assume you can't
so just spawn it and compare?
unless you really need a code for that
I am sending the base prefab into my validator and checking all the gameobjects, two of those gameobjects will always be the prefab itself and the fbx, and I want to ignore those.
What do you mean change the base fbx?
I wasn't helpful
I just told that if you open the fbx you can manually compare what was there at the start and what was added later
because you can't override fbx prefab
GameObject go = PrefabUtility.GetCorrespondingObjectFromOriginalSource(transform.gameObject);
string assetPath = AssetDatabase.GetAssetPath(go);
if (assetPath.EndsWith(".prefab") || transform.name+".fbx" == assetPath.Split("/").Last())
{
continue;
}
This is the best I can come up with, the prefab can be skipped as it has .prefab and the fbx can probably be skipped because the name+".fbx" will match the last part of the asset path on that object. But if some crazy person on my team names a model the same as the fbx file it will be skipped due to a false positive
I would avoid that issue because every time I use an fbx in a prefab I am unpacking it
wonder if that makes something worse
That's a nice idea but it would break so many other unrelated things
like what?
We have lots of custom pipeline tools that would make that a very dangerous change and break stuff :p
You are losing the link to the fbx so it could be hard to reload or locate?
I recreated a shortcut from Unreal Editor that lets me press ctrl+b to select the selected object in my project. So it's nice to have the fbx in the prefab so I can find it instantly
Unreal has so many nice quality of life tools that Unity just completely lacks that you have to make by yourself
you should be doing with that question in code-advanced I feel
Like snapping selected objects to the nearest meter on the grid
offtop but why switching
It's not my company ;)
I keep forgetting it's not all about small indie devs...
tbh.. i prefer unity b/c of how easy it is to create my own tooling.. vs Unreal which i'd have to rely on things just being there to begin with
snapping object to the grid is relatively easy, anyway.. move it to a single digit transform, then toggle grid snapping w/ 1 unit
at the same time Unity is kinda closed while you are free to modify Unreal source
...not like most people would do that tho
lol, its all fuggered up
you'll have to take it to google... modding topics aren't allowed
is there a Unity modding Discord I wonder
probably ¯_(ツ)_/¯
Well I'll delete it then
I'm not interesting in the modding part, I put that for context
I'm interested in the Unity specific loading part.
Like creating and assetbundle, and then loading the .anim from that
Or Resources.Load somehow?
does anybody know why i cant drag enemy bullet position into the enemy shooting point in the enemy parent prefab it worked i cant get it to work no matter what i did using online tutorials
b/c you can't drag scene objects into a prefab
You can't put gameobjects in a prefab that are not part of the prefab
Choose the best way to reference other variables.
Your explanation's better SpΔwn
thank you guys i will take a look at that
I have a little Grid-Based-Game, and want to add a little Shopsystem, where the player can buy objects and place them on the grid. I wonder is there a kind of await return. The simple breakdown would be, Button-Press -> [ShopScript}triggers buyObjects function ->(funtion "paused" until player picked tile)Player can selected Tile on Grid -> [TileScript]This (Grid)Tile set a Varible in [ShopScript] -> buyObject funtion continues (either if Varible X != null after retrun). Do you have a idea what i should look up on google to do such thing, is async teh answer?
You dont' need this to be async at all. Just event you can subscribe to then unsubscribe when the tile is picked
okay i look that up, thanks
more or less a rough example
public class Purchase : MonoBehaviour
{
[SerializeField] private TilePicker tilePicker;
public void InitilizePurchase(){
//stuff
//open buy menu
tilePicker.OnTilePicked += OnTilePicked;
}
private void OnTilePicked(Vector3 pos, MyTile tile){
tilePicker.OnTilePicked -= OnTilePicked;
//do something based on tile?
}
}
public class TilePicker : MonoBehaviour
{
public event Action<Vector3, MyTile> OnTilePicked;
//probably needsto be with in update with a bool you toggle when purchase needed or other way to detect input / selection
private void PickingTileLogic(){
if (Input.GetMouseButtonDown(0)){
var tilePos = Grid.WorldToCell(worldPos);
var tile = Tilemap.GetTile<MyTile>(tilePos);
if (tile){
OnTilePicked?.Invoke(tilePos, tile);
}
}
}
}```
of needs null checks and other stuff but should get the idea going
Hey folks! Despite my adding a Rigibody component with Constraints to my camera, when controlling it I can still do movement I shouldn't be able to. Can someone review my video and offer advice? What I want to achieve is to move along a flat horizontale plane using WASD, and use the camera to aim at things - but never "fly" towards where I'm aiming. Thank you!
here's this code for beginners before creating a Button To Exit The Game
that's not good code - why are you sharing that
how are you moving the camera?
or actually, rather; you should probably have the camera as a child so it can pitch freely, separate from the player
You mean the game exiting when you click the mouse anywhere?
Hey! I was originally using this:
void Update()
{
//Get player input
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
//Moves the player
transform.Translate(Vector3.forward * forwardInput * speed * Time.deltaTime);
transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime);
}```
But now I'm looking into a Rigidbody and adding force. Which works better, but I have to now figure out how to properly slow down.
So now I'm using this
//Get player input
forwardInput = Input.GetAxis("Vertical");
//Movement
playerRigidBody.AddRelativeForce(Vector3.forward * forwardInput * speed, ForceMode.Force);
oh, right
i forgot that doesn't have a button trigger
hold on i gotta fix that
ok fine
maybe just add linear drag to the rigidbody?
pitching the camera up would change the forward direction, so see above ^
Thank you, I will try that. Is that called Linear Damping now in Unity btw?
Here's a fun way of doing forces:cs Vector3 targetVel = /* your desired move velocity */ Vector3 diffToTargetVel = targetVel - rb.velocity; rb.AddForce(diffToTargetVel * accelerationMult);
You can adjust the "stiffness" by adjusting accelerationMult
The idea behind this is that you only add the force that is needed to reach the current target velocity
yeah looks like it
Linear drag is also an option yeah. Try stuff out
Cool thanks! Seems to work.
Thanks, I will try this.
...are you trying to implement a jump?
just say so lol
you have the check for detecting a space press
just make it jump/animate
there's quite direct methods for both, have you tried researching them?
So... you press space, and you teleport this object to 0, 0.1164255, 0?
Also, put an f at the end instead of casting to float
Huh, they disappeared
can someone help me convert this coroutine to a async await Task function?
{
float et = 0;
int i = 0;
List<Coroutine> routines = new();
while (i <= diceComponents.Length)
{
et += Time.deltaTime / iterationDuration;
if (et >= iterationDuration)
{
Coroutine r = MoveAllDice(diceComponents[i].transform, duration);
routines.Add(r);
i++;
et = 0;
};
if (i >= diceComponents.Length) break;
yield return null;
}
yield return null;
}```
Hey. I’m trying to add the text (TMP) to the question txt.
I tried sending the QuizManager over to the “Question Txt”, but it’s not working.
your variable type is incorrect. your variable expects a legacy Text object, but you are trying to assign a TMP_Text object to it
it was all an illusion
Do I have to start over then?
Change the variable type
no, you have to change the variable's type to the correct one (TMP_Text)
Thank you. Where would it be located?
do you know what a variable is?
the place you made it
in your script, you change the variable type
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables
Guys i am using playerprefab to save data i want to save data for scene 1 when i go to scene 2 and when i come back to scene 1 it loads
don't crosspost
not going to lie i don't understand C# att all, can someone maby help me out? i just want a quick walk tru.
Guides are linked in the pins
ohh realy? ty did not know that. going to check that out. ty for helping me the right way
better learn then #💻┃unity-talk message
just get familiar with oop concept the rest is similar in all languages
ty i will try all of this, hopefully i get somhere in unity. ty for you help
are you using 3d project for quiz game?
No.
I’m using 2d.
Universal 2d Core.
My apologies, I’m doing a project my professor assigned me to do. I got everything right, but all I need to do is change the variable.
and you know what a variable is, yes?
there are beginner c# courses pinned in this channel. perhaps start there if you didn't pay attention in class
Never mind.
I got it!
Thank you.
you should still go through the beginner courses if you plan to continue using c#
I have a problem with a USB joystick; it works in the editor and Windows build, but when I build it for Android, it stops working. I am using the new input system.
im super sorry if this is the wrong Channel, but i got no clue where to put it: my Game Scene - even when everything is empty - can only reach 15 fps at max... i never had that before, any idea why? Target Framerate is 60fps and "Gfx.WaitForPresentOnGfxThread" takes like 50% of the time per frame
That's a GPU bottleneck. What do you see in the GPU module of the profiler?
public override void PerformAction(Character caster, Character target)
{
base.PerformAction(caster, target);
caster.AnimationController.PlayAnimation(animationStateName);
caster.StartCoroutine(WaitUntilAnimationFinish(caster));
}
private IEnumerator WaitUntilAnimationFinish(Character caster)
{
yield return new WaitForEndOfFrame();
var stateInfo = caster.AnimationController.GetCurrentAnimatorStateInfo();
while (true)
{
Debug.Log($"NormalizedTime: {stateInfo.normalizedTime}");
if (stateInfo.IsName(animationStateName) && stateInfo.normalizedTime >= 1f)
{
actionFinished = true;
yield break;
}
yield return null;
}
}
why is the normalizedTime always printing 0, even when the animation is playing properly? That results in actionFinished never set to be true. I want to set it to true after my animation finish
public AnimatorStateInfo GetCurrentAnimatorStateInfo()
{
return _animator.GetCurrentAnimatorStateInfo(0);
}
thats what my profile says, im struggeling to read that clear tbh, never used it before
found it... my nvidi control panel screwed EVERYTHING. even with it beeing set to 50fps its locked to 15 for magical reasons. i set it now to 250 and i get clean 125 frames (no clue why its halved but idc... works)
It depends on the vsync settings as well.
How do I override height settings on an object that spawns on a spline?
by default, when attached to the spline, my train is spawing below the track
when I change the train position to +10 on the Transform properties (of the train itself) then it looks correct BUT when I press play it re-takes the variable from the spline and goes back under it. Any ideas?
Where is the pivot of the train?
I don't know what that is, I'm a complete noob 😕
Are you trying to call a function when the animation ends?
The point in space that the model uses at its position.
Where do I find that out? Also, it's linked to the spline, that seems to be the issue (I want it to follow the spline, but I want to add +10 to its height, the train that is, instead of it taking the spline height which is -9)
The issue is that your pivot on the object isn't at the bottom of the train. That's the point that is aligning with the spline.
But if you want to hack around it, when you position the object when evaluating the spline, just add the height offset to it as well
Where would I add the height offset, though, as I'm not sure where to do so
Code
In a modeling program such as Blender
Alternatively, you can create an empty object and put your train in there and offset the train inside.
Then use the root object on the spline
Okay, that makes more sense to me I will look at that
Stop crosspointing, thanks.
@tall glen you can save data inside player prefs or in file (if u want save that data on disk) or you can use DontDestroyOnLoad method
ik that i can say private voide Start() and then Savedata for example but how do i do it with scene entry and exit
if playerprefs cant find anything, does it throw an error?
no
private void OnSceneUnloaded(Scene scene)
{
// Save the game data before leaving the scene
SaveGameData();
it looks something like that
but i want it to load and save between switching scenes
You can use OnApplicationQuit for example
Already did
Or just in method before you are loading scene
Don't use PlayerPrefs to pass data between scenes, use a DontDestroyOnLoad object
i dont understand
you should have public void LoadScene(int sceneId){Save(); LoadScene(sceneId); }
PlayerPrefs leaves its data behind in the system's registry, storing a lot of data in there means a big chunk of space your average user probably won't know to get rid of
Imagine if simply playing a unity game tied up a gigabyte of your hard drive without telling you that stuck around even after you uninstalled the game
cause i cant find a youtube vid thats acctually good
Don't destroy on load will make your object undestroyable when you change a scene it will exist with data u set in previours scene
It's unlikely you'll store that much data, but you still shouldn't. Player prefs should be for exactly that, preferences. Things like graphics settings, window size, etc.
If you need data to go across scenes, better to just put that data on a game object and pass that entire object between scenes
no i dont want it to go actoss scnes
Doesn't require writing anything to your user's OS Registry that way
Then what are you trying to do
it can still be same
That's what "across scenes" means
i tried to do many save methids
but it all didnt work
this is the only one i acctually understood
If you just need to keep some data between the scenes,do what digiholic recommended.
Sorry Im blind your code is fine you have already SaveGameData in correct place inside SwitchScene()
but when scene 2 is loaded and cutscne is done i come back again to scene 1 and i have to do the missions again
and its a loop
there might be a bug in your code for the next level
its not a next level
@tall glen
Probably because there's an issue with your saving/loading logic. Or just the game flow logic in general.🤷♂️
As for what Digiholic recommended, there are plenty of videos on that:
Then start simpler. Did you go over the beginner pathways on unity !learn?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no
If you don't k ow the basics, you're gonna keep on struggling.
Do proper learning before continuing your project.
i just need to do this then ima publish the demo
No
Learn to use unity and C# and it will benefit you, as that is what happens when you learn most things. #💻┃unity-talk message
I'm sure P-A-I-N knows the basics
i was making a game
thats why i choose unity
cause im familiar
also i learned some of c#
the one i sended was called a method
Check the LoadGameData just debug it if it will be loaded in first scene in right place or it is rewrited somewhere to starting values when you are loading first scene
im gonna just watch a vid
Ok maybe you might have missed something in the code
like digiholic said
i do that all the time
You could load the second scene additively and disable the first scene, then when the cutscene is over unload the second scene
thats a good idea
i dont understand
like in timeline i put activation track
You can have problem when scene rewrite data to default and saving it in wrong place so you LoadSaves after it was set to default values
P-A-I-N maybe that might be the bug right there
cause there will be 2 cameras
wait i record
here
dont mind colliders
theyre easy
i fix later
@icy crag @polar acorn @valid violet
@teal viper
im trying to rebind controls using PerformInteractiveRebinding , however I set up reference only for InputBinding, how do I get InputAction and the binding index from there ?
Hmm they are not the most recent log statements from your video. Do you get your debug log statement ‘Player reference is null. Cannot load position.’ logged while changing back to your first scene?
i couldnt find how in here https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/ActionBindings.html , is it not possible and i have to ref the input action and index instead ?
does anybody know how i could make it so that the enemy spawns properly instead of in a huge rectangle i tried implementing some things from online but i couldnt get it to work. im assuming its to do something with the frames per second and thats why its spawning alot but im not sure what to do about it
Trying to following a youtube guide but I'm already stuck. I can't find the sprite mode and pixels to units option anywhere? Anyone know where
confused, why cant i see pixels to units
is the problem that the enemy spawns rapidly or is it a problem with enemy position?
Also please format your !code correctly
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
not a code question, but those options are on the texture's import settings not on the sprite renderer. select the texture in your project window and the import settings will appear in the inspector
ah i see my bad, thanks for the help
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
{
if(m_CanGrapple)
{
m_CanGrapple = false;
player.GetComponent<LineRenderer>().enabled = true;
player.GetComponent<LineRenderer>().SetPosition(0, player.transform.position);
m_rb.AddForce(gameObject.transform.right * m_grappleSpeed, ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
m_rb.freezeRotation = true;
m_rb.constraints = RigidbodyConstraints2D.FreezePosition;
player.GetComponent<LineRenderer>().SetPosition(1, gameObject.transform.position);
}```
im using a line render to show a connection between my player and my grappling hook however when i first draw it it draws a line randomly to the middle of the screen and then snaps back to the correct place does anyone know why this might happen
i think the problem is that the enemy spawns rapidly
you said it spawns in a rectangle and this is not what you want but I do not see any instantiation code for the enemy, you would need to provide such code so we can see why it does this.
And please use the bot for code formatting.
sorry im having a hard time with the pasting service
yeah somethings up with my cookies sorry for the troubles ill try again a different day
Does anyone know a way to prevent this from happening? What happens is that when I rotate the sprite it moves and doesn't stay in the same position. I am using spriteRenderer.flipX to rotate it
that means that the sprite's appearance is not centered on its pivot point
Do you mean changin center for pivot?
no, i mean the actual sprite's pivot point in the sprite editor
In the sprite editor it is set so that it is in the center
show it
okay, now actually look at where the pivot point is in relation to the image
so you see that circle in the center? that's the pivot point. what do you think will happen when you mirror that image along its pivot point
I assume it happens because the edges of the sprite are larger than the sprite itself, but I put it that way because when using larger animations like hitting it looked like it was moving while doing the animation, I don't know if you understand. Is there a way to prevent that from happening so i can set the borders normal?
you need to adjust its pivot point so that the sprites always line up correctly
Set the pivot in the position you want to remain constant when the sprite mirrors or changes
I solved it, thank you
So after I add this single line of code, the ball fall down extremely slow, what might be the reason for this ?
you're setting its Y velocity to 0 which is resetting gravity
since you're probably using unity 6, and this is clearly 2d, just assign the linearVelocityX or whatever that property is now called
Do I need to create a new vector to assign it ?
wouldn't that be the Y axis
no, since you would want to leave the y velocity up to gravity
no, it only assigns the one axis so you only assign a float to it
tks
in the screenshot he's setting the linear velocity Y to 0
which is what you don't want to do
yes...
right so they need to only assign to the linear x velocity, not both axes
2d has properties to assign each axis individually (in unity 6)
ah, didn't know that was possible with 2d
If anyone else had this problem, the issue is that Unity C# does not support Func<> and you need to use Action<> instead.
unity absolutely does support Func
There is nothing about Unity that stops you from using Func
huh? there is nothing wrong with Func<> . . .
were you trying to return a value?
it sounds like you probably had a method that returned void with a GameObject parameter, which is indeed an Action<GameObject>, a Func<GameObject> would be a method with no parameters that returns a GameObject
you probably used the incorrect delegate and received an error . . .
Well I tried Func<> several ways with no success, and Action<> works perfectly.
show what you were actually trying to pass
because you prolly used it incorrectly, that's all . . .
{
pointer = new PointerEventData(eventSystem);
pointer.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
raycaster.Raycast(pointer, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
foreach (var result in results)
{
if (result.gameObject.CompareTag("ItemPane"))
{
function(ItemPane.GetPaneFromObject(result.gameObject));
}
}
}```
Action is the typical/normal way to pass a method . . .
i'm just gonna go ahead and link this again because it explains exactly what you were doing: #💻┃code-beginner message
If you just had the above code and instead had Func then you just misunderstand what Func does
Very likely
i would've looked up Action and Func to see what they are/do and their differences . . .
I read several stack overflow questions claiming that Func<> works as a function delegate, tried it, looked at more and saw this: https://stackoverflow.com/questions/54772578/passing-a-function-as-a-function-parameter
again, very likely im wrong but my code works and thats enough for me
Func has a return type other than void. Action has a return type of void
Is the physics engine stable ? Do they have a way to calculate a fixed time between updates or they rely on my hardwares ?
What do you mean calculate a fixed time? Fixed Update is advanced by a fixed time, there's nothing to calculate
if it wasn't stable, i don't think they'd have much of an engine for anyone to use . . .
Encapsulates a method that has a single parameter and does not return a value.
https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=net-9.0
Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
https://learn.microsoft.com/en-us/dotnet/api/system.func-1?view=net-9.0
The function variation shown above simply does not take an argument but the other variations do.
Action and Funcs differs in that Funcs always expects something to be returned.
also, they already calculate a fixed time between frames . . .
Yes, that's one, I was just wondering since I have to add time.deltatime to Updates because it's framebased, and if I dont need it for fixedupdates, then does that mean fixedupdates has a way to calculate a fixed time accross all the machines ?
If you want to understand FixedUpdate a bit better I have a page that describes it https://unity.huh.how/info/fixedupdate
Fixed Update runs only when required. It's run multiple times a frame to catch up to the current time, and it's skipped when ahead.
This page is awesome ! Thanks for the recommendation
not sure where my arrowheads have gone, but whatever 😄
Vertx shameless self promotion 😛
nah, this is just godly awesomeness . . .
they've seen people ask the same questions and problems more than anyone. it makes sense to have a document for all this stuff . . .
dont need to think too hard if you just shove everything into fixed 
heck, i created one when i first started unity for beginners . . .
is that an actual recommendation I should follow ? honestly I still dont know when I should use fixed or updates
It's a joke, but a good way to think of it is you're more likely to break stuff putting stuff that belongs in fixed update into update
as far as unity physics (rigidbody) modules go
Stuff that belongs in update -> Polling input, and lerping visuals
If you use Unity's (now) standard input then you can cut out the input polling, and if you download a tweening library (or coroutines) you can use that over lerping in update
how do check if a variable is worth more than another by a certain amount
Hey I'm trying to make a boomer shooter where the player's gun is a 2d image and animation. would I add a canvas to the player and have that run the gun animation?
or would I do something else?
Wdym by "worth"? In what currency?😅
Check if the difference of both variables is larger than your certain amount . . .
You would do something like
if(a > b && a - b > minimum difference){
Function here
}
If I understand your question right
Probably not a canvas. A sprite renderer with an animator should do.
would I have it shown in the camera?
Overlay or second camera is a good idea, but if you do want some scene lighting then you need inject the ordering of it manually into the pipeline
gooootcha
Just get the absolute result of a and b and check that against the minimum difference . . .
wait a second camera?
yes thats what i meant thank you
You still need to handle if b is greater than a . . .
From the way he worded it, it sounded like they wanted to only check one way around. I could definitely be mistaken though
id like to check if the difference between two variables is equal to or above a certain amount :)
You could be right. I don't know, so I'm covering all bases . . .
Then you don't need a > b condition.
Just a - b > c would be enough
True true
Then get the absolute value of a - b and compare that . . .
why are we doing minuses
That gives you the difference . . .
I want to make a ball jump while it's on ground, can someone give me a direction in what should I do ?
You should search around for tutorials depending if you want to use unity's rigidbody physics, or making a kinematic ball where you control the bounce more directly
So I have this code, the horizontal movement is fine but the ball don't go up all the time when I press w , why is that ?
Input should be queried in regular update.
tks
Do you guys use the new input manager ? Is it necessary for a professional job ?
yes, no.
If knowledge of the new input system is part of the job requirement then yes. Best learn it now to future proof. The ild input will be deprecated at some point.
How can I make the objects appear above a panel in unity 2D?
Hey I'm using assembly definitions, but I referenced assembly2 to assembly1, but I cannot use the classes in assembly2's scripts in script1 but I can use assembly1's scripts in script2. How can I fix this without circular reference?
I’m confused if you reference assembly2 into 1 you should be able to use types and methods from 2 in 1’s code
But I can't do 2's code in 1
I need them to reference each other
only way to do that is by using Reflection
Right, so what do you advise that 3 to be
Circular references are bad design that should be avoided
Split the parts from one and two that are needed in both into a 3rd assembly
Thanks
What movement methods should I use for a moving platform ?
physic based velocity changing or transform.translate/transform.position
I'd just use parenting
but if you're asking specifically the platform's movement, Vector3.Movetowards in a lerp is a great option
Or vector2
If you want it to interact correctly with physics, it should be moved by physics. Velocity is fine, but you can move it more directly with MovePosition
How do i make it so that everytime i create a script inside a folder, the script body will automatically be inside specific namespace ? Something like assembly definition root namespace, but i dont want to use assembly definition for that
Just type it in
I mean, i wonder if there is automatic way to do it
Just to make my hand less tiring
There is a way ye
Ok thanks i'll read that
Eh, i read that, but it apply to all script, not just the one inside a folder
Why do I need to multiply a vector with time.deltatime if it's in fixedupdate ? ( this is taken from the unity manual )
That is not what i'm looking for
I mean, one time will come when you'll have to use assembly definitions, its good design
If i use assembly definition inside another assembly defintion, does the other asmdf reference the asmdef inside it ?
i want to avoid asmdef because the folder is already inside an asmdef and i dont know how nested asmdef work
You can use auto reference and then it will yes. But you can add it manually as well
I don't like to type out namespace everytime either, I just don't do it, and at the end of the day I do it for all scripts I made that day 😂
I'm that lazy
welp, looks like manual is the way then
For now, but you can give it a search
So if you changed the fixed update rate you would get the same distance
Your IDE should be able to help. At least with Rider it'll try its best and automate it, and at least if you used the refactoring tools to add it it'll use autocomplete
I use visual studio 2019
What is the fixed update rate ? Do they vary machines between machines ?
Fixed update rate is the rate at which fixed update is invoked
The rate set in the project settings under Time
So If I don't change the fixed update rate, it doesn't matter ?
Not particularly, your speed might not be in m/s in this specific case. Many other cases are multiplied internally so multiplying again would be bad. It really depends what API you use
you can't, you would have to write an editor plugin for it
Multiple ways
For example, make a third assembly that is shared between the two
In cases where you hook content onto another assembly you can have assembly 1 reference interfaces which assembly 2 then hooks onto through extension methods provided by assembly 1
But most importantly, circular references usually mean that you are trying to decouple too heavily because they both depend one achother
So optimally it should just be 1 assembly if there's no logical way to have a shared assembly, or hooking
For example, if it's just general utils used then you might aswell make an assembly for those specifically
It would help if you explain your use case more clearly so a proper solution can be given
And pls don't use Reflection like SteveSmith mentioned. You should not have to use Reflection and it is going to look horrible. The only case would possible when you involve attributes to hook onto content
Literally have this issue in a project at work where they have two projects and they just use reflection now to get content. It's impossible to debug or unhook now and I can't use the project because of it
Can you declare a private variable that is the name of another object?
yes as long as they are not in the same scope
Can you elaborate?
do you knoow what scope is?
Sort of. I have a page open that I'm reading on Variable scopes (unity docs).
a matched set of braces { } is a scope
a variable must be unique within a scope
ok
this is basic C# so you should be using the C# docs not the Unity ones
ok
I've been trying the following line of code and variations of it, but I keep getting errors. Is there another way to go about this or do I just need to tweak something?
private string shapeClassF = gameObject.GetComponent(name) ;
any idea why I get the same coordinate in the debug regardless of the position of the card?(same position for every card spawned and set to grid)
you are trying to get a component into a string variable. That can never work
I just want the name of the component. Isn't that a string?
You don't get the name of a component with GetComponent<T>().. you get the component
wdym by name of the component
do you mean name of the object?
Yes, I mean the name of the object