#💻┃code-beginner
1 messages · Page 353 of 1
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
oh wait nvm
clearly i can't see colored squiggly lines
ur formatting threw me for a loop
hi i need help adding like
a basic timer + score counter to a simple platformer
im a full noob at unity so bear that in mind
what sort of timer score counter..
give more details..whats ur goal?
the timer should just count down from like 60s to 0 and start the end script
the counter should probably just be time + some collectable
when i mean the game can be basic i mean its extremely basic
soo a timer that counts down continously.. and then a collectable that adds a bit of time to it?
yeah
pretty much
this is current progress
its just a small school project but deadline is pretty soon
you'd need a private float to countdown from, in update you could subtract from it:
timeRemaining -= Time.deltaTime;
then all you'd need is a conditional to end the game
if (timeRemaining <= 0)
{
EndGame(); // call your end game function
timeRemaining = 0f; // set the timer to 0 in case it overshot it or something
}
and ofc, a function to add ur time back to it..
public void AddTime(int seconds)
{
timeRemaining += seconds;
}```
then you can call the function and pass in how many ever seconds u want the logic to use: `AddTime(3f);` or `AddTime(yourVariable);`
would this be a seperate script
also sorry for the bother i just cant miss the deadline
probably.. you'd preferably want it to be a singleton or something so it could be accessed from anywhere.
whats singleton?
but, it could be on the thing collecting the pickups
right i also need actual pickups
so i would need help with that too if possiable
if you could link me to a video i dont want to waste ur time
and u could just use the collision to get the script from the player.. playerTransform.GetComponentInChildren<NameOfScript>();
for a pickup system?
like a trigger collision type dealio?
I'd just have the script on the player so it detects the pickups, it's faster and only requires one (already existing?) script
you could find a decent one on the internet just by search those 2 terms
except where he uses tag == you should instead use CompareTag("TagOfObject");
if ur only doing 1 type of pickup you could jsut have the detector on the player that when it detects a trigger collider it destroys the collider and just adds points to itself.. that could be done in the same script actually
{
AddTime();
Destroy(other.gameObject);
}```
would this happen in void start or update?
or am i doing this completly wrong
OnTriggerEnter is a special unity method
oh
how and where would i put that script then
inside a script ideally
which one, thats up to you to figure out
if you're doing 2D you need the 2D version
as it is the object has no scripts other than box collider 2d
renderer and transform too i guess
I kinda just got here, can you give me a TLDR what ur trying to do ?
just add a collectable + timer + score
it goes in the class, alongside update start etc, same syntax as those
bit more noob language
you're gonna have to learn the lingo at some point 😛
it's a method
not if i dont stay in this path 🔥
a function that you declare inside of a class or struct
class is basically a blueprint to what your object will do
functions etc are what it can do
public class YourScript : Monob..
{
Update(){}
CustomFunctions(){}
OnTriggerEnter(){}
}```
unity has built in methods in Monobehaviour
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
as you can see OnTriggerEnter is part of many others
well unity calls them Messages
cause they're similar to how event works basically hence the naming convention
update runs every frame, thats where the timer would go..
but OnTrigger.. gets called by Unity just like Update.. and Start.. etc.. so the brackets line up inside the Class { } wrapper
i have no clue about what any of u are saying
the closest idea of what i get to do is like
😅
copy my death script and put it in the same place?
do you want to learn or are you just going to say "I know nothing" over and over
the latter is a great way to continue to know nothing
not awfully keen in learning right now since its a deadline
if it wasnt deadline restricted i would be down to learn
then i'm not awfully keen in helping if you're just hoping I write the code for you
they said it was a school proj, and its almost deadline.. you know, the normal MO
the point of the project is to prove your understanding
yeah we're not going to help do homework for you
wish it was just homework atp
help you fix issues and understand them if you want to learn
i would suggest consulting
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
and
2D btw **
ok better question which is probably easier for u guys to answer
could i just basically edit this to a destory and remove the transform
ah, good, then see spawncamp's link
yae,
You mean destroy instead of setting position?
pretty much
destroy the object*
the coin in this case
yes
other.gam.. = ("ACoin") // a tag <--
Destroy(other.gameObject); <-- the other (which is a coin)
the answer is always defaulted to yes, you can
wouldn't that destroy the collider ? 😛
inside this what does other count as
Hey so both the list of player pawns and the multigrid controller are serialize fields so I know that the newPlayer and multigrid aren't null but for some reason the final line of this throws me a null reference exception, what could it not be seeing?
do i just call it the coin?
then multiGridController is null
thanks thanks
u can name it w/e as long as u reference it correctly
It shows up here, how could it be null?
the thing above it is null..
maybe you have a copy of the script with it unassigned?
is that supposed to be?
can you show the complete error stack btw
it's a part of something I haven't started implementing yet
also freaky we got the same playmode color tint lol
Purple is nice lol
ohh so it is netcode
more than likely you are spawning a copy with it unassigned and the function is running
but yeah I'd check how many you got in playmode
also multiplayer questions do belong in #archived-networking or in the pinned NGO server
well dont think its a shock to you guys but its not working i guess
character is just moving straight through it
guess what OnTriggerEnter is for 3D
oh
I figured it wasn't a multiplayer issue
Box2D physics engine vs Physx engine, aint gonna happen
whats the 2d varient?
have you read anything sent to you for the past 15mins?
more like i understand none of it
huh
quick question, whats that suggestion box that pops up when you start typing in code? It has stopped appearing for me so I have to guess or look up the correct code each time
intellisense
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
ty friend!
so you dont want trigger anymore ?
i thought that was what u were telling me to do
no I was telling you that there is 2D versions of everything physics related
since unity uses two seperate engines for each
Box2D vs PhysX (3d)
if you're doing 2D stick to the 2D methods
look what spawncamp sent you #💻┃code-beginner message
alright ill check it
Yep I think i fixed it ❤️
i managed to fix it (sort of), but i still sink a very small bit and have to press space multiple times when trying to jump
recently switched to a new pc on windows 11 and now when coding in c# doesnt show me syntax errors or auto fill stuff and most code just remains white even tho it used to be blue and stuff to represetned it was an actual thing, assuming theres a setting or update i need to get it to show that stuff but im not sure any help would be appriciated
same code before and after
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Howdy all, so just trying to learn how to use Unity and how to use scripts with classes.
Big forewarning i am fairly new and i think i have made a beginner mistake in using multiple scripts but not too sure, trying to inherit classes and what not.
TLDR in this just trying to make a weapon system with some modularity.
So i made a Wep Data script that holds the weapon data, than a AmmoData script that holds data for ammo and finally a script to just see if in a Example script to just see if it works.
No errors in the data scripts but in the Example script it says the AmmoData is a type but not valid in this context.
This is all in the constructor, nothing being actively used yet.
Now i tried to put the ammo data in the WepData Script to maybe see it was just an reading error of some kind that didnt work. Tried some ammoType._BaseRifleAmmo and that comes with a seperate error.
So hitting the wall just a bit unsure how to approach it.
The pictures in order should be: Wep data, Ammo Data, Example.
Not sure if i used the PasteOfCode right: https://paste.ofcode.org/PDzvsS3vXe7YPuMySN3The
No errors in the data scripts but in the Example script it says the AmmoData is a type but not valid in this context.
Please share the full error message including line number
Same for your other errors
well, to start with, a Monobehaviour cannot have a constructor
You cannot have constructors on classes that derive from MonoBehaviour!
My bad forgot to share:
'_ApRifleAmmo' is a type, which is not valid in the given contextCS0119
Thats the sole error so far.
You left out the line number
full message
Compile errors have filenames, line numbers, and column numbers
to show you exactly where the error is
may be a good idea to check what coin.gameObject.name actually is because 100% it is not "Coin"
i have no clue on how to figure that out
what should i do to find out?
rather i just need that to be true and run the delete script
Everything in your example here EXCEPT for "RandomWeaponExample" should NOT be a MonoBehaviour as far as I can tell.
MonoBehaviour is only for making components. Components are the things you attach to GameObjects.
Debug.Log ?
Also, still waiting for those full error messages
Right okay, apologies.
So its just in the editor, using Visual Code.
I havent looked in unity since nothing so far is using it, as it says theres an error in editor.
Line 11 on the example
which on Pastebin (The link to that site) is: 90
With the error being
'_ApRifleAmmo' is a type, which is not valid in the given contextCS0119
giving a check in editor it does mention about namespaces but i would prefer to focus on the current error.
But right Monobehaviour can be removed from the example script
you find it by searching the Unity documentation, google is a good starting point
That constructor takes a parameter:
AmmoType ammoType
This means an actual instance of AmmoType or a class deriving from AmmoType.
What you tried to pass it was the name of a class which derives from AmmoType.
It's a bit like if I asked you to hand me your laptop, and instead of an actual Laptop, you gave me a bunch of schematics for how to build a laptop.
its calling "player"
Really the short story here is that you are using inheritance incorrectly here
this is not what inheritance is for
What you actually want is just an AmmoType class and a bunch of instances of that class with different values for its fields
what? what is calling player
e.g.
AmmoType subsonicAmmo = new AmmoType("Subsonic", "Slower than sound ammo", 1, 5, 50);
WeaponStat = new WepData("new weapon", "I am a weapon", 0.2f, WepData.FireMode.SemiAuto, WepData.WeaponType.Pistol, subsonicAmmo);
@shadow briar
nothing there calling player
What's logging that
Also - again, none of these classes should be MonoBehaviour except the "Example" class.
Okay, so this object has collided with something named Player, not Coin, so it won't be destroying it
right i need it to be inversed
would the script go to the player instead of the object then?
What object is this script on
coin currently
So, Coin probably isn't colliding with Coin
i have very little understanding of what the code is actually doing
OnCollisionEnter2D is called whenever two solid objects collide. This object is one of them, and the other one comes from the Collision2D variable (that you can name whatever you want)
So, you can check what object collided with this object, by checking that Collision object
In this case, the script is on Coin, and it's populating the data about the thing that collided with it in your Collision2D coin variable
so how would i be able to achieve the inverse of this basically
Right okay, sorry for the hassle with such beginner stuff, so a big thanks for providing an example and just saying im using it incorrectly - my generalised idea was taking inspiration from Tarkov with how there are loads of sub types since been on a binge with it and all that
But personally im curious if i could create Subsonic in the AmmoData Script and just reference that.
Check if the thing that collides with this object is a player, and if so, delete its own gameobject
might need a bit more help on how the syntax etc actually works
You could define it wherever you'd like
This is actually a great use case for ScriptableObjects
ScriptableObjects would let you create different AmmoTypes (and weapon types!) as actual assets in the editor that you can drag and drop, modify in the editor via the inspector, and reference from scripts etc.
It's not a great use case for polymorphism/inheritance though.
Well, you already know the syntax. you're currently using it
copy paste 🧌
Then consider looking at the pins and trying the intro to C# course to learn what it all means
Hm hm alright thanks for the answer
And alright i'll give scriptableObjects a looksee later.
many thanks for it and once more sorry for the inital hassle
100% what digiholic said, you need to know the fundamentals of C# and software development before working on code. If you copy-paste, the code will reach a point where you cannot make any changes due to lack of understanding it
atm im just trying to make the game to finish a project
its not me trying to actually learn it right now
That's a tough situation to be in. What's your timeline?
What's the point of finishing a project if you're not learning anything from it?
less than 9h
currently
i dont mind learning it later but deadline takes priority now
I am learning C# will it be everything I need for a VR/ online game?
i mean, you need to learn Unity itself, animation, audio, modeling, etc
In the coding side of things, I understand it will require that stuff as well
I think you might be falling into a trap of "i'll just complete the project now and learn everything later" but the entire point of the project is to learn
If you don't know how to code, you're pretty much asking us to do your project for you
yeah, well unless your question is do you need other languages? then no C# is all you need
if i dont sugar coat it pretty much yeah
Yea, does VR need a new language or is that not the case?
Out of curiosity, what class is this for?
computer science
Awesome
CS 101, GME 203?
Well, you won't find anyone willing to dig through that code for you for free. If you really intend on cheating your way through, maybe hire someone on Upwork or a similar platform
unity basically c# only
well mind if u help with this specific part
this is litearlly all i need help with atm
if i can get this working i can do the rest 95%
What kind of help?
ive been told to effectively invert the objects?
rn its tryna destroy the player
ofc i want it to destroy the coin instead
but i literally have 0 clue on how to even after trying to learn on links sent
Well, you're checking if the object has a "Coin" name. So it shouldn't destroy your player(unless it is named "Coin".
the issue then is it does nothing
the coin just remains floating in place
Well, where is that code then?
I'd assume that you're trying to destroy a coin when the player collides with it?
afaik this is the only code i have based for it
I mean, what is that script attached to
Think logically then: can the coin collide with itself?
no i know that part
what im trying to do is if anything comes in contact with the coin
then delete the coin
Okay, then how do you reference a gameObject that the script is attached to?
no clue
Try researching a bit. Not gonna help you if you don't even want to put in minimal effort
i can try look for that then hold on
is this what im meant to be looking for
No.
Check the MonoBehaviour API docs.
Or rather Component API. Specifically the available properties:
https://docs.unity3d.com/ScriptReference/Component.html
just started to follow a pretty good video instead
however new error bit specific to it
In this video I'll show you a quick way to make a coin pickup and UI to track how many coins the player has picked up!
Check out my previous 1 minute tutorials: https://youtube.com/playlist?list=PL8Wm13VrP6MRPpAMqzblFZ3HVgXACltQs
if there are any tutorials you'd like to see, feel free to leave a comment below!
Fol...
video in question ^
the errors im getting
that's a warning, not an error . . .
wrong ss
find the script mentioned, go to line and look for a reference variable. if more than one, log and check each one to which is null . . .
afaik nothing is wrong?
coinText is the only thing there that can be null
so the obviousl conclusion is, coinText is null
why cant my script, score, access the public boolean lostGame, defined in my other script, playerCollision?
lostGame exist in a different script called playerCollision. you are not referencing that script . . .
your score has no idea you're trying to access lostGame from playerCollision. you're accessing it like a class variable from score . . .
To access a variable belonging to another script you need a reference to a particular instance of that script.
Note that every instance of playerCollision is going to have its own copy of the lostGame variable
so you need to tell it which instance by referencing it
I assumed that a public variable was the exact same for every script
You assumed incorrectly
like how variables work in TI-BASIC
it's not, that's normal and makes a loty of sense . . .
https://unity.huh.how/references/serialized-references.html
I know, I am saying this way of doing this is strange, not that it is wrong
you misinterpret my statement
You can make a variable that behaves that way in C# if you want, but it's usually not a good idea as a beginner
Basically BASIC is not an object-oriented language
how do I make a reference?
references to objects are a concept in object oriented programming
we both sent you links. read them . . .
read the links we both shared
will do
literally not a single word of this makes any sense
I will go look for something on youtube
study time!
thanks anyways
for my crop growing game should the crops grow while the player is offline or only online with short times?
how could i program in unity to calculate offline time, do i have to subtract off the date and time since last online?
Well, that's a design question.
So you want that to happen? Do other systems simulate offline time? It would be weird if only one thing in the game was simulated offline.
Pretty much, yes
How to check if sphereCast is hitting anything but a specific object tag?
With an if statement.
not really sure what "hitting anything but a specific object tag" actually means though
Physics Raycasts can only hit one thing and that is Colliders.
well yeah
Well Spherecast returns a boolean, Im asking how to make the boolean only true when the thing it collides with is a collider with a certain tag
you can't change what the raycast returns
bool hitSpecialThing = false;
if (Physics.SphereCast(... out RaycastHit hit) {
if (hit.collider.CompareTag("CertainTag")) {
hitSpecialThing = true;
// Or just do whatever you need to do here and omit the bool variable
}
}```
Just... you know.. check for it
yeah it would be the only thing in the game simulated offline
You'll want to also look into layermasks
Does anyone know how to change a string from an input field into a float for a static variable?
Static variable seems irrelevant,but you need to parse it
float.Parse or float.TryParse
Look them up in the C# docs
I tried to fix it and looked through the docs but it says that Parse is not in context and can not convert float to string
show what you tried
public static float timeAmount;
public InputField insertTime;
public void ChangeTime()
{
timeAmount = Parse(insertTime.text);
}
all my code
but i fooled around with it
so you didn't look at the docs then
i have no clue whats causing this^
any ideas?
i can take any ss u might need but i dont get this shit
yeah i get that but
how do i link the script properly
wdym by "link the script properly"
for both of the scripts above its just simple counters and timer
you do realize i don't know what the contents of your code is so i cannot know what is null to tell you how to fix it, right?
and have you even figured out what variables are null using the steps in the link?
so you just didn't bother dragging the reference in there
huh
wdym "huh"? you did not bother assigning the variable
literally look at your screenshot?
not following
you sure it doesn't need some flashing lights or anything to help draw your attention to your screen?
show the code
does this object have a TMP_Text component on it
then you've got another of these components in the scene without one
look at your logs, you'll likely see that log from Awake printed more than once
your console is set to Collapse
ah
make sure there isn't a (2) at the end of the line
explain this
yes and that proves my point exactly. you have 2 of those components in the scene
one of which does not have a TMP_Text component attached and should be removed since you should only have one ever since it is a singleton that doesn't bother doing any checks to see if one already exists
how do i fix this?
your string contained characters that were not able to be parsed as a float
all i inputed was 4 in the input field
put this on the line before the float.Parse call: Debug.Log($"'{insertTime.text}' is {insertTime.text.Length} characters long and can be parsed into a float: {float.TryParse(insertTime.text, out var f)}"); then show what it prints
oh wait i just went back and saw insertTime was the input field, you'll need to access the .text property for it in that log
but i suspect this is u200b making its appearance again
`Debug.Log($"'{insertTime.text.Length}' you want before the call for parse. then what do i do with this {float.TryParse(insertTime, out var f)}");
obviously at each point in that log where i used insertTime you just have to add .text to it
then show what it prints
well you clearly didn't follow my instructions. but i updated the message so you can just copy/paste it
you'll also need to use a different variable name since you apparently use terrible names and called something f already
no errors
okay if there are no errors then run it and show what the log prints
i told you to put the log on the line before your existing float.Parse call
then save the code so it recompiles and try it again
also get your !IDE configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
same error here
sooo what should I do??
screenshot the entire console window
congrats, you have been cursed by the TMP_InputField hidden character! when you parse it (and ideally you should be using tryparse if a player can input anything into the input field), you need to trim the \u200b character from it
have you just never read any documentation before?
you don't copy/paste that line into your code, that is the method's signature. the method you need to call
i get that (i think) public string Trim (char \u200b); is that it?
not even close
oh gosh
please go through the beginner c# courses pinned in this channel
good idea
Having a small difficulty, multiple boxes are getting grabbed at once when I interact with "E" on the hitbox of the first one. How could I fix it to separate them?
using UnityEngine;
public class BoxPushPull : MonoBehaviour
{
public float pushPullSpeed = 4f;
public float playerNormalSpeed = 7.0f;
public float playerGrabSpeed = 4.0f;
private bool isPulling = false;
private Rigidbody2D rb;
private PlayerBase PlayerBase;
void Start()
{
rb = GetComponent<Rigidbody2D>();
PlayerBase = FindObjectOfType<PlayerBase>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (!isPulling)
{
isPulling = true;
rb.bodyType = RigidbodyType2D.Dynamic;
PlayerBase.SetSpeed(4.0f);
}
else
{
isPulling = false;
rb.bodyType = RigidbodyType2D.Static;
PlayerBase.SetSpeed(7.0f);
}
}
if (isPulling)
{
Vector2 movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
rb.velocity = movement * pushPullSpeed;
}
else
{
rb.velocity = Vector2.zero;
}
}
}
instead of checking for input on every individual box, you should instead check for input on a component on the player, then you can use a physics query like a raycast, overlapcircle, etc to find nearby interactable objects and interact with those specifically
because right now, all you do on every single box is just listen for input and start reacting as soon as there is any input regardless of whether the player is even anywhere near them or not
where 2 save data & sort it if folders in game directory can't be written, folders in Application.persistentDataPath r also can't be written?
what do you mean they cant be written? if you have a specific error you should share, or explain why.
So in general make a script for an Interactable section placed within the player, and use that to detect any nearby interactable items with a raycast perhaps?
yes
I'll try and figure out what to do in regards to that then
Do you intend to have double backslashes in your path? Also if you use Path.Combine you don't need to specify any slashes and it is generally much safer due to that
I'm currently trying to make two objects(guns) attached to my camera always visible but the models always clip through the floor. How do i make them always visible
same issue & this /s work, because directory is creating
nevermind i did it
hello coding gods
im trying to make a script that checks to see if the other player is ready, is this a question to ask in the unity multiplayer networking server? or can I ask this here?
There is a #archived-networking channel you can ask in. Asking networking stuff in the beginner channel is usually worrying
Gotta say what networking solution you are using though, and what you mean exactly by "ready" (just loaded, having completed some action, etc)
thank you thank you i'll ask it there
good morning guys. i have a question, if i want to add part of an scene as addressables is better to use Addressables.LoadSceneAsync or Addressables.InstantiateAsync?
what happens to a reference to a destroyed gameobject? is it set to null?
no, the reference is still there. it will just throw a MissingReferenceException if you try to do unity things to it, and it will be equal to null when comparing with the == operator
TownController.Instance.Scroll = null;```
the DeleteItem function calls Destroy(gameobject)
just wondering if I still need to set it to null after?
if you want it to be actually null and not just reference the now-destroyed object, then yes you should
yeah it needs to be null, I'm checking it in other places
destroyed objects do still equate to null using the == operator
ah
unity has overridden the == operator to check for destroyed objects so a destroyed object will return true when compared to the null literal with that operator. this is why it is always recommended to use that operator to null check a UnityEngine.Object variable rather than things like the null conditional operator, is operator, or null coalescence. none of those use the overridden == operator and unity cannot override the behavior of those other operators so using any of those other operators with something that may be destroyed but not immediately explicitly assigned to null will end up potentially throwing exceptions
not a code question #archived-lighting
oh srry
Facing problem with the word random plz help me
you have Random from 2 different classes, so you need to pick only 1
how that can be done
remove the using statement for the one you dont want, or use using Random = UnityEngine.Random;
read the Name resolution ambiguity section of this page: https://docs.unity3d.com/ScriptReference/Random.html
still not spawning randomly
why would you expect it to?
is there a way to immediately end a coroutine from an outside source
instead of stopping it
like if im using a coroutine to tween two values
is there any way to add some sort of interrupt that would instantly make it go to its end result
to end a coroutine, you have to stop it from running . . .
oh, you mean to complete its function (purpose). just create a method that stops the coroutine, and sets the end result of what ever it does . . .
i was thinking of setting a boolean or something within the coroutine that would exit the loop or something like that?
how can i add breakpoints to code in unity that would pause the editor?
How do I make sure that all the Input Field only accepts integers?
Debug.Break()
It has a setting for this in the inspector
Especially if you are using TMP
Ah got it, thank you
you dont make it be random
I assume this means you fixed the initial issue?
So whatever the issue is now is different. Considering sharing your !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.
how to make this timer would be slower and realistic seconds https://hastebin.com/share/avovucabit.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
minus it by deltaTime
instead of 0.05
timer -= 0.05f; // decrement timer by 0.05 seconds each second
This is called in Update. The timer will be calculated correctly just if your Update runs exactly 20 times per second
Either decrease the timer by Time.deltatime, as was mentioned above, or manage this behavior with the Coroutine
Hey, I want so that a line renderer's position is exactly where my cursor is, on update.
This didnt work: https://paste.ofcode.org/UBAXn5qXuhMuTTNTAtfSyF
does this even run?
put a debug.log
at the top before mouseposition =
It runs, but the line is just short
so is secondPoint true just based of nothing at the beginning?
I got it.
Local space was on
Guys for Unity I only need to know C# right
Yes
thats what Unity uses yes
Is it easy to switch between it and C++
Nope
not quite, you need to know C#, .Net and the Unity API
I mean depends on ya
most languages are easy to switch between
How much time do I need to learn all three
And be able to use them correctly
I guess it depends too 😭
depends on you, id say 6 months to a year
2 weeks to 1 month for a basic level
C# is easy, it's only syntax. .Net is huge so you will never learn all of it, the Unity APi is big but with effort 6 months for an experienced programmer
So as someone with zero experience can I be able to make my first game in 3 months
Just a simple mobile game
you can make your first game in 2 days, depends what your making and how you make it
other programming experience?
Nope
then 3 months is unrealisric
depends what your making "simple mobile game" can be many things
without programming experience you need to learn programming not just coding, that is no easy task
Like the ones you see in ads where they are just stupid
Not my goal
i mean for example a flappy bird you can make that in your 1st day after installing Unity
What about a game like soul knight but without online servers
that would take a while
a basic prototype you can make in probably 1-2 weeks depends how you use your skills
Ok thanks and do you recommend any material to go and learn from
depends what your goal is
if you are trying to literally just make the game
follow tutorials on each thing your implementing
otherwise theres some pinned in this channel or !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I starting by watching a 12 hour course on C# to at least have the basics before going into making the game directly
sure up to you, me personally i would watch a MAX 2 hour a video but if you feel like you can sit through 12 hours of C# then that would probably be helpful
Yes totally taking rests between them not gonna finish it in a day 😭 but i expected 3 months would be enough to get me on track and ready to upload games
try this first
https://techdevguide.withgoogle.com/paths/foundational/
choose Java as the language as it is very close to C#
Ok then thanks for the recommendation
hey guys what are the ways to make a parallax effect? for instance, hollow knight layered their backgrounds in 3D but some do it using programming. whats the best method?
theres many videos on it on youtube
doesnt hollow knight use an isometric camera? so layering it in 3d does nothing
im not sure about that but i saw this on the unity website
thats not 3d
thats just them looking around the scene in 3D view
to showcase each part of the background
yeah thats what i meant
they're further apart but this alone does nothing if youre using an isometric camera, so they are probably moving them through code and using their Z value for how much they should move
probably
you just set the Z of them and move them based of your player moving with the camera
each part different speed
Well outside of a “normal” camera there’s no other way to do parallax
theres no other way, is there?
Either you let the physics of perspective do it or you move things at different speeds sooo
and making your camera non-isometric screws up your entire view and the game no longer looks the same so you cant do that either
Yeah you’d have to design the game around that
Actually I checked and it also happens in preview it's just less noticable so these logs are relevant to the character swerving to the right while going backwards.
Hi, I'm a beginner in Unity.
I usually use Godot, but for a game, I need to use Unity.
So, I wanted to know how to load all the videos of a project (FMV) before the game starts. This project will be hosted on a website, and I'm not sure what the best way to play those videos is.
idk about videos, but this doesn’t sound like something where you’d want to use unity
it sounds like youtube
Guys im spawning an object in the Worldspace and assigning its position to the mouse position but they are located differently, how can I fix it?
You’re gonna need to send a pic or vid of what’s happening
Add Component -> Box Collider
does the ball also have a non-trigger collider on it?
so that's a no
a rigidbody is not a collider, it just simulates physics
Looks like it's working exactly as it's supposed to
https://paste.myst.rs/idno2w1p
https://paste.myst.rs/n0v1hbn7
Any idea why my character swerves to the sides while going backward? I've linked the movement scripts and the debug above.
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
yes, that is as expected if the ball has no collision
And some code of how you spawn it?
Right, because colliders collide with colliders, which your ball does not. Since your ball has no collider, it's supposed to do that. Meaning it's working as intended
remember how i specifically asked if the ball had a collider, then you showed that it did not so i pointed out that it does not
2D game?
yep
Guys I need you helppppp, I'm making a roguelike game that has multiple scenes and DontDestoryOnLoad function working between each scene. Any suggestion for restart function? I need to make the player go back to the first scene when dies and all the data needs to be reset (Everything back to the default setting).
Can you send a bit more of the code afterwards?
theres only this
destroy the DDOL object then when you load the scene it was originally in again a new instance will be created that you will then use
So im making a VR game but when Im making my code it comes up with these errors talking about needing to convery to a new SFK style for it work in C# Dev kit. Any clue on how to fix?
configure your !IDE so that it will underline your syntax errors for you
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
For example, im on scene(2) now, and PersistenceManager is the object I assigned the DDOL on, I want to go back to the start scene after I click the restart button and I did sth like this
public void Restart() { Destroy(GameObject.FindGameObjectWithTag("PersistenceManager")); SceneManager.LoadScene(0); }
Am I doing right?
does it have that tag?
yea its same as its name
and have you tried this?
I tried and it looks like the saved object in DDOL did not get destroyed
so you see two of those objects in the DDOL scene?
yes
are you sure that it has the PersistenceManager tag applied to it?
Honestly, singleton time? Might be easier than tag searching and maybe duplicating
yes
show the full inspector for the object
holy hell you have so many DDOL objects. but it's clearly working, there's only a single PersistenceManager in there after the restart. now you need to do the same for all of the other DDOL objects that aren't getting destroyed on restart
yea lol, im making a roguelike game tho
yes but the things still there
that doesn't mean you need every object to be DDOL
what do you mean?
roguelikes generally don't persist many things from run to run 😉
its a student project mate hahaha
i don't really see how that is relevant
the things already in DDOL did not get destroy
my dude, you only destroyed the PersistenceManager. now destroy the rest like i just told you
yo
{
if (collision.gameObject.CompareTag("PlayerSlap"))
{
ChildHealth--;
Debug.Log("Child Killed");
}
}``` is there a reason why my code isnt rlly working? im making an attack system bassically if i click the mesh renderer and the collider turns on, that works as needed this doesnt work and idk why
Do you get the log
no thats the thing i dont
thats why i added it
this is the gameobject thing
Then this object never collides with anything tagged "PlayerSlap"
as u can see the Tag is PlayerSlap
yeah but i dont see why not? i have the gameobject with the tag as PlayerSLap
Okay, now show the object with this script on it
I may be wrong but I wanna say you don’t get a collision if the collider is turned on while already inside the other collider
seriously go through this
I tagged it as EnemySlap Cause if they touch you then u lose HP thats works fine
Okay, so since this one has the rigidbody, is this object the one moving? How is it moving?
yeah its moving
Is it moving via rigidbody
am i really the only one that saw it?
Oh yeah also collision vs trigger is what box is trying to subtly say
no
Took me you pointing it out ngl, but I’d have done more debugging
Oh wait there's two obvious things wrong
i have the rigidbody for physiscs
Nah they said the collider is turned on first
I saw that it was disabled but they said it enabled I didn't even check the rest of the collider
no the collider turns on if i clcik
which works
i checked
I know, I saw that, I assumed that box missed it, but he actually saw the real problem
Yeah
heres proof that if i click they turn on
Yeah that's not the only checkbox you should be concerned with on that collider
oh is it cause i have the isTrigger Enabled?
it means you need to take a look at this again: https://unity.huh.how/physics-messages
Check the docs for how to make an on trigger enter function
but the thing is the script that has the OnTrigger is the AI following me, and the Box Collider of the Child Isnt a trigger
wont that affect something?
you know this can be answered by reading the information in this guide, right?
Nice
and the death thing works too
lets goo
quick question again
this is the code i have paired to the slap thing right
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;
public class Stats : MonoBehaviour
{
public ChildFollow CF;
public float Health = 5;
public Slider HealthBar;
public GameObject Slap;
public void Update()
{
HealthBar.value = Health;
if (Input.GetKeyUp("mouse 0"))
{
Slap.GetComponent<Collider>().enabled = true;
Slap.GetComponent <MeshRenderer>().enabled = true;
}
}
}
yeah well how can i turn off the Collider and meshrender again? i was thinking of making a float variable and a bool to check if the ColliderIson and if it is the float to go down by Time.DeltaTime and once it reaches 0 to reset the float variable and set the Colliders and meshrenderer to false and also set the bool to false
is there like a better way to do it?
No real need to subtract deltatime, just track the time it started and then subtract that from either Time.time or Time.realtimeSinceStart(?)
why dose the destroy function destroy my script instead of the gameobject the script is attached to? the val here is ref through a interface
what you have there will destroy the gameobject, provided you actually save the code
how can i impliment that into my code cause i only worked with DeltaTime so idk anything about Time.time
using System.Collections;
public class Example : MonoBehaviour
{
public GameObject projectile;
public float fireRate = 0.5f;
private float nextFire = 0.0f;
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(projectile, transform.position, transform.rotation);
}
}
}``` this is what i found in the unity docs but this is only a delay beetween shots whilst i need my slap to be on for like 0.5 seconds then turned off again
(I’m on my phone so a (?) means I’m not 100% sure about the type/name, IDE and docs should catch it)
Assign Time.time to a double(?) when the slap starts, then on each update check whether the time between that assigned time and the current time is .5s and if so disable the slapper
Oh nvm.💀 it turns out my team member instantiated a GO that looked exactly like the bullet upon enemy death.
Why doesnt unity want to recognise [serializedfield]?
Because there is no such thing
I had no issues using it before tho. And the video I watched also uses it.
make sure your !IDE is configured so you don't make silly spelling mistakes
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
how can i make it so the SlapTime goes down?
Show the video that uses it
i think they mean [SerializeField]
Its for VR but goto https://www.youtube.com/watch?v=TJ8yk5vVwI0 (13:40)
🎮 This is a wrap up of my How to make a VR game series cut to a single video for easier follow 🕹️
🔹Asset Links🔹
1️⃣ Unity Asset Store Free Asset: I will be using this great free asset from the Unity Asset Store in this tutorial: https://goo.by/f2w1f
or
https://assetstore.unity.com/packages/3d/props/polygon-starter-pack-low-poly-3d-art-by-synty-...
I know they mean that
Its used as a float
they aren't using serializedfield there
i found the issue
you know its bad when even i know how to fix it
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 162
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-5-21
SerializedField doesnt exist
SerializeField Exists tho
again, get your !IDE configured so you don't make these silly spelling mistakes
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
whats the diff beetwen time.time and time.Deltatime?
what do the docs say about each of those
havent rlly read the docs about them someone just said if im working with time to use time.DeltaTime
Read the docs then. That should ALWAYS be step 1
There are significant differences
your first thought when you don't know what something does should be "i should check the documentation" rather than "i should ask what these do in discord"
oh
i just checked
wait then shouldnt i be using time.Deltatime instead of time.time?
Deltatime is the time it took since the last frame
You can make a timer using either of them
time is just the time since the first frame
yeah but i dont need to count time from the first frame
Both would work, it’s just more conventional to make a timer by comparing the time to the runtime rather than adding up the Deltatime
If you store the current time since first frame, and then some amount of time later, count the time since first frame, what mathematical operation could you use to find the difference between those two times
We don't know WHAT you need. You just said you are "work[ing] with time"
ye im working on attacks, basically i need a gameobject to be turned on for 0.2 seconds then turned back off
Nah they said it a bit ago
dayum ur like the first person to stand up for me lol
Meh just correcting a misunderstanding. Some people hop in and don’t realise it’s been a slightly long convo
Done it myself before
Ah, it was blocked by another conversation
Yeah
i did smth and it works
That sounds like it would be best for deltatime or waitforseconds in a coroutine (cache the waitforseconds though)
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;
public class Stats : MonoBehaviour
{
public ChildFollow CF;
public float Health = 5;
public Slider HealthBar;
public GameObject Slap;
public float SlapTime = 0.5f;
public bool isSlapOn = false;
public void Update()
{
HealthBar.value = Health;
if (Input.GetKeyUp("mouse 0"))
{
Slap.GetComponent<Collider>().enabled = true;
Slap.GetComponent<MeshRenderer>().enabled = true;
isSlapOn = true;
}
if (isSlapOn == true)
{
SlapTime -= Time.deltaTime;
}
if (SlapTime <= 0)
{
Slap.GetComponent<Collider>().enabled = false;
Slap.GetComponent<MeshRenderer>().enabled = false;
isSlapOn = false;
SlapTime = 0.5f;
}
}
}
prob not the best way to do it but it works
God reading this on a phone is painful lol
lol sorry
Yeah that’s one way of doing it
i mean it works
Nah I’m lazy my pc is like a metre away
lo
But yeah if it works that’s the main thing
I think there’s a way of doing it that’s considered “better” but I think it’s just because it’s become a standard rather than any other reason
https://gdl.space/alalabivoh.cpp i made this function for a script in my game that should handle the grip of a tyre on the x axis. it works on normal cornering but when it drives straight the forces overshoot and it begins to wobble really heavily. how can i solve this best?
this was prob the first time where i didnt get bullied when i needed help
Sorry I was distracted. I could bully you now if you want
Sometimes programmers can be harsh but usually it comes from a point of wanting people to learn for and by themselves rather than constantly outsourcing
I've seen you helped many times without being "bullied"
Have not seen any bullying, but of course I have not seen your EVERY interaction
I’m struggling to quickly see why, but have you tried adding more debug logs or using the debugger?
I guess you have the gizmos but I can’t see those
Actually wait no
I had this issue too
I would do the Vector3.Dot with tyre velocity.normalized
Yes and it weird I think it mby starts with the fact that floats aren’t 100% precise and it carries it into the tyres trying to correct it or something
I will give it a try
Is this a code question?
#1180170818983051344 would be more appropriate then
Ok ty
man i couldnt have gotten a better response
works now tnx
logical if you think about it but never crossed my mind
hello, new to the coding side of unity and wondered if anyone could help - I have a character moving and idling in 8 directions, however, i cant seem to make the character idle in the 3/4 positions, it defaults to either up/down/side. tried looking elsewhere for a solution and cant find anything. thanks in advance:)
current script if helpful
Had me pulling hair out when it caused me issue because the docs didn’t seem to properly reflect what it actually does
yeah the only way i knew about it was through a yt vid that talked about it. should be documented better tho
!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.
oops apologies! https://gdl.space/ekebuxagir.cpp
https://gdl.space/lusezuvoje.cs
Getting very confused. Its declared as a monobehavior class yet its saying it isn't. Can't see any syntax wrong on it? Was working moments ago, closed my computer and no its doing this?
any errors in the console?
thats a warning not an error
yeah but thats all I am getting
delete the script from your game object and then add it back
screenshot the entire console
Filename, class name, all match
the whole window
I have a class containing properties:
public class MovementModifier
{
public float SpeedModifier { get; set; } = 1f;
public float DurationModifier { get; set; } = 1f;
public enum IgnoreModifier { None = 0, PopUp, WaitDuration, PopDown }
}
I want my method to accept the MovementModifier object as an optional parameter. So if a MovementModifier is not provided, it'll use the default values I've set into the properties.
I know how to make simple data types like int or string optional, but how do I make MovementModifier optional?
public void Foo(MovementModifier movementModifier ????????)
{
//Do something
}
ok thought errors might be hidden but seems there is none
yeah, very confused. Even tried restarting unity but its still doing this?
try deleting the class name, going back to Unity, then adding it back and saving the script then add the script
same error
idk i think thats all the steps there is to fix it? unless there is something im missing
Looks like removing PlayerInput library fixed it?
cause now its working. No idea why its doin that though
The optional value must be a compile-time constant. The only thing you can use here is null, and afterwards check if it's null, and assign a new instance of that class with the default values you need.
eg.
void Foo(MovementModifier movementModifier = null)
{
// Note: '??=' does not work reliably with anything deriving from 'UnityEngine.Object'
movementModifier ??= new MovementModifier();
}
An alternative would be to make an overload that doesn't take the parameter, and call the other method that has the parameter with the value you want.
void Foo() { Foo(new MovementModifier()); }
void Foo(MovementModifier movementModifier) { /* ... */ }
Great explanation, makes sense. Thank you.
I had some issues to debug my code on windows so i checked on my mac and was able to debug it but then i notices there are differences in the project even though it's the same repo.
- on the mac the min for scale is X2 and on the windows is X1 does it matter?
- the canvas size on the mac is smaller (320X568, and on windows it's 400X711) and it seem like only 4 buttons out of 5 are showing (in horizontal layout), does it mean i have a problem or is it just because there are some differences with the project settings and I shouldn't be developing on 2 OSs
For the first point, I don't know what you're referring to with "scale" (it can mean multiple things).
For the second point, that means you haven't set up your UI anchoring correctly so it adapts to different screen sizes
It needed to force recompile. Chances are you changed a name of something and the codebase didn't get the message to recompile. Another thing that can force a recompile is to intentionally introduce a syntax error to a script and save it, then let it fail and go fix it
i set the anchor on the panel, should i have done it on the canvas too?
The Game View might just be too big for it to render at that 9:16 resolution, if you resize it down, can you scale the display down?
Cannot set anchors on a root-level canvas. The current preset is set to scale with the screen width, anchored at the bottom. You should move your question to #📲┃ui-ux if you have more issues
if i change it from aspect ratio to fix resolution it allow 1X i guess its really just mac screen dps issue haha
Is this the right area to ask about scriptable objects or is that more #archived-code-general
and thanks a lot 🙏🏼
Here is probably fine
problem solved
Thank you 🍪
Alright, so I'm developing an RPG and I want to have an On-Contact battle encounter system. I was wondering if I should store encounter information in the enemy, give that to a scriptable object, and then transfer that information to a "Battle" Scene, or if that's improper usage.
I know SOs don't store data permanently, but they should store for while the game is still open, right?
You can do that with a class that doesn't derive from anything
It's usually best to keep ScriptableObjects immutable (when created they should not be modified)
So I take the info from the enemy's encounter data, transfer it into a non-derivative class, and then reference that info into the new scene?
If you already have a script on an object that you persist through scenes with DontDestroyOnLoad(), then you can use that to transfer your data
I see, thank you for the help
Need help with this script i got 3 scenes like Level 1, Level 2 , Level 3 how do i make that in diffrent level diffrent time seconds would be like level 1 would be 30 in level 2 would be 20 in level 3 would be 10 https://hastebin.com/share/eqovohavan.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I can't access my enum property. What am I doing wrong?
public class MovementModifier
{
public float SpeedModifier { get; set; } = 1f;
public float DurationModifier { get; set; } = 1f;
public enum IgnoreModifier { None = 0, PopUp, WaitDuration, PopDown }
}
MovementModifier movementModifier = new();
movementModifier.?????
Because you've defined the enum but you don't actually have a variable of type IgnoreModifier
An enum is a type on its own, like int or string. You need a public IgnoreModifier Mod { get; set; }
You've made the type but you aren't using it anywhere
If you're going to use it outside the MovementModifier class, consider moving it outside to its own file.
public class MovementModifier
{
public float SpeedModifier { get; set; } = 1f;
public float DurationModifier { get; set; } = 1f;
public enum IgnoreModifier { None = 0, PopUp, WaitDuration, PopDown }
public IgnoreModifier MovementType { get; set; }
}
I think I have it now. I didn't know that it behaved as its own data type.
an enum is a Type, like a class or a struct
yep, exactly, it's its own data type
Basically, I want my player sprite to pass through enemies but I still want him to take damage from said enemy is there anyway that i can achieve this?
A trigger Collider sounds pretty much like what you need
use trigger colliders
BTW that sounds like you would need either the enemy or the player to have two separate colliders:
- One for general interaction with the game world (ground, floors, etc)
- A separate trigger collider for the enemy/player damage interaction
how to fix this error i only have one LevelManager Assets\Scripts\LevelManager.cs(4,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'LevelManager'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Remove a duplicate instance of the LevelManager script
You can't use a class name twice
(unless you put them in different namespaces)
but i don't have
you do
You clearly do
Great thing about computers is they do exactly what they're told and they tell no lies.
Maybe I'm stupid, but shouldn't this code place an object at all the corners of a rectangle? (the red dots in the image)
position is the green dot on the image
for(int j = 0; j < 4; j++)
{
GameObject obj = MonoBehaviour.Instantiate(gameObject);
obj.transform.position = position + new Vector3((j % 2 == 0 ? halfSizeX : -halfSizeX), 0f, ((j - 1) % 2 == 0 ? halfSizeZ : -halfSizeZ));
}
The second image is what I get from this
Nope, it'll place two at opposite corners. You should use two nested for loops, it's more readable
i have quick question so i have an empty object with arms and gun under it but so there are two different animators how do i make them work at the same time i have made my gun and my arms a different animation but they work togheter
when j%2=0 ,(j-1)%2=1 you must get halfSizeX, -halfSizeZ, when j%2=1, you must get -halfSizeX, halfSizeZ
alright, thanks for the explaination
I changed it from (j - 1) % 2 == 0 to j >= 2 and that works
float offsetX = j % 2 == 0 ? halfSizeX : -halfSizeX;
float offsetZ = j >= 2 ? halfSizeZ : -halfSizeZ;
obj.transform.position = position + new Vector3(offsetX, 0f, offsetZ);
btw there are only two states generated when you do j%2 , but you want -1,-1 -1,1 1,-1 1,1 = four states, technically impossible to produce -1,-1 -1,1 1,-1 1,1 from only a single j%2 operation
The pattern I usually see when converting a one dimensional index into two dimensions is:
int x = i % width;
int y = i / width;
I still cant figure it out
I figured i could use OnTriggerEnter but
Why would you make a separate serialized reference to the player?
What's the point of that
Compare the tags with the CompareTag method
i see
CompareTag should be used yes but that's just an optimization
it won't change the behavior
This code doesn't make sense as is.
That was a simple suggestion
yeah i figured
I have no idea then
Hi what ami doing wrong here please https://gdl.space/jetigocewa.cs i cant seem to hit Debug.Log("loading the data");
Hint - don't have a separate serialized reference. There's no need for it. OnTriggerEnter2D gives you a reference to the object you intersected with.
Is any of the code running?
What's logging in the console?
Are there any errors in the console?
Failed to load player data: End of Stream encountered before parsing was completed.
so do i call close steam at the end
Look into TryGetComponent. You won't even need to use tags if you do that
Although you can. In the case of the object being wrong, validating the tag is slightly faster than a failed trygetcomponent call.
Not a big difference though
Hello, is there a way to do something like this
boolean = expression
to check if a boolean is true, I don't want to do If (expression) then (boolean is true or false)
Why not just use File.ReadAllText instead of faffing about with streams?
not heard of that one before
boolVariable = boolExpression is completely valid
like literally, you wrote the answer here as your first sentence
Maybe share what the error is?
That will work as long as the datatypes are correct
below is a bool, the other 2 are floats
Then there's no problem
it says can't convert bool to floats
if you have an error, please share it with the class
do i do ==
if this is the case
Are you reading what I'm writing?
You used the wrong datatype for below
you wrote float
it should be a bool
I'm asking if you can make a bool true or false based on an expression without using an if statement
They both return a boolean. Assign the needed boolean to the expression.
bool yourBool = IsSomethingTrue();
bool result;
float x = 5;
float y = 6;
result = x < y;``` This works fine
you just did it wrong
you did this:
float result;
float x = 5;
float y = 6;
result = x < y;```
no, i result in my case is a bool
provce it
and it says can't convert bool to float
prove it
Show the full script
I think you made a mistake
because your error message implies you made it a float
{
Overseer global;
Player player;
float footY;
float platformY;
BoxCollider2D bc2d;
PlayerControl playerControl;
public bool below;
public bool down;
public bool jump;
// Update is called once per frame
void Update()
{
footY = player.transform.position.y - 0.5f;
platformY =
below == footY < platformY;
if (down && jump && below)
{
bc2d.enabled = false;
}
else
{
bc2d.enabled = true;
}
}```
you put ==
i changed it to == after I asked
it needs to be = and you need to delete this nonsense
not quite
platformY = below == ...
right now what you have is float = (bool = expression);
and you cannot convert a float to a bool
is your IDE configured?
without the platformy yes
yea I fixed it
nice 👍
thank you all, I should have finished that first
it happens :D
remember statements are terminated by ; not by new line
Hello,
I am currently facing a problem. I've attached recordings of my actual game progress. The problem is that on the top half of the grid (that is isometric) you can see that the placeholder isn't appearing unless I kinda put it next to an already placed bloc, in that case only the face against an already placed bloc is kinda appearing. It started to appear after I imported and used an asset pack called low poly water. I did some debugging but I feel like it's not a code problem or anything like that, just in case here is a pastebin of the PreviewSystem. I've tested to place cubes with just a normal blue plane and it works just nicely (as you can see on one of the 2 attached videos), so it seems to be the low poly water plane from the asset pack, maybe a shader problem but I'm not quite sure, if anyone has a clue I would be happy to hear it.
Disclaimer : I'm currently learning unity, and especially integrating graphics, for a long time I made games for fun without using any assets so I kinda understand the coding part but not the visual things.
is there anyone who willing to help?
Are you aver calling AddTime? Is it ever running? Use Debug.Log to check
nah it doesn't add
So if you're never calling AddTime that's a good reason why AddTime might not be getting called
im gonna try calling it and see if it would work
Sorry, I started to answer and got a phone call..
But. what you have looks like it will work..
- Make sure the OnTriggerEnter2D is on an object with a BoxCollider
2Dor some other2Dcollider - Make sure there's a Rigidbody
2Dsomewhere on the setup.. (mine is on the Player in this example) - Make sure that
isTriggeris ticked on the Collider on the GameObject the script is attached.. - Make sure that your
PlayerTag is applied to Other GameObject.. and that its spelling and capitalization match exactly
using UnityEngine;
public class Monster : MonoBehaviour
{
public float damageAmount =10f;
public float health = 100f;
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log($"Something collided with our Trigger.. {other.name}");
if(other.CompareTag("Player"))
{
Debug.Log($"That 'something' matches our tag..");
// Take Damage to Monster
health -= damageAmount;
}
}
}```
Hi everyone, I'm trying to get an object to follow my mouse in a room (like first video). What I want is for the object's position to change to where the mouse is moved. I am doing this by casting a ray from the mouse. When the ray hits a collider the object's position should change to where it hit. But when i hit play and click on the object, it move along the ray that is being cast, starting at the collision (hit.point) and traveling towards the camera. Once it reaches the camera it starts over at hit.point and repeats. When I move the mouse the object's position changes to the new hit.point and moves toward the camera (second video). Anyone know how to fix that, or is there any other way to move the object like the first video? Thanks!
ur code must be doing that.. can u show the code where u position the object to the hit location
My code:
public class Trash : MonoBehaviour
{
private bool _dragging;
private Vector3 _originPos;
private void Start()
{
_originPos = transform.position;
}
private void Update()
{
if (!_dragging) return;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var mousePos = hit.point;
transform.position = mousePos;
}
}
private void OnMouseDown()
{
_dragging = true;
}
private void OnMouseUp()
{
_dragging = false;
transform.position = _originPos;
}
}```
hm now the sprite just through the ground
your raycast is hitting the object itself when you spawn it
Use a layermask to exclude it
hey, i'm missing the correct android jdk, sdk, ndk and gradle for my new unity version which I downloaded through the unity archive, online it sais to download in through the hub but there it won't let me add modules, where else can I find the right versions for this?A
wont let you add modules why?
idk just not an option
click installs
then topr ight should be add modules
yeah I know but it's not there
screenshot it
you cannot add modules to a Editor that was not installed via the Hub
i see, it only works with LTS i think
it is an lts version but I had problems downloading it through the hub as the install would just stay stuck in an endless loop, then I decided to download through the archive which worked fine but now I can't add the modules
I mean I could just download them manually and put them in the right folders but i'm not sure where or how to find the right versions for this unity version
Click add modules and check jdk, sdk... was installed or not, if installed, u should try uninstall the Editor and reinstall it. It work for me
I know, but if i use layermask, the object just move on the floor or wall only! 😦
go back to the archive page and download the Unity Installer for your Editor Version, that should allow you to add modules to the Editor
the add modules isn't there for the version i'm using now 2021.3.38
this is the only option it gives me using the installer, after that it just starts
Works for me
Did you just download the editor again, not the Unity Installer like I said?
downloaded the exe again from 'https://unity.com/releases/editor/whats-new/2021.3.38#release-notes'
also downloaded the android build support component installer
Dont do that
Use whatever layers you want.
alright gonna restart pc and try again and run unity hub as admin now as I read that could be the reason the install in hub never finishes
I just realized that using raycast only allows objects to move on colliders. But I want it to be able to move freely like in this video. Maybe I should try something else, do you have any suggestions for this problem?
Plane.Raycast
This video seems to use an isometric view with an orthographic camera
So the depth doesn't really matter
Whereas your game is using a perspective camera
So that's going to change things a bit
I figured it out thank you anywayss
Oh, i see. I will try it. Thanks a lot!!
i don't know how to make it work it doesn't work for me i want when the obstacle respawns the timer would add 20 seconds
Try logging Timer after you add time to it
Update = I just set the render to be 3001 (right after the water plane) and it works like a charm
hi im working on the 2d beginner unity course and i have an issue
ive just updated my character moving script to now have the move left as an input action
but its saying that InputAction doesnt have a definition for isPressed
u have to regenerate ur c# class
each time you add to ur input actions u need to regenerate the class (make a new version of it)
its IsPressed not isPressed but the guide had it wrong so when i copy pasted it in it didnt work
so the references exist
what do you mean regenerate?
like make a new save?
I thought once you generated it one time, any save changes gets added to this dynamic class on its own no?
i am having a problem where the boxcolliders collide without touching eachother, this is the bug and the code
i can't say for sure.. I've had other people do it to solve their issue.. and the last time i used the c# class I would have to regenerate.. The action map could be updated automatically.. but not the c# script.. I would think that'd be something they'd add or something that should be the default functionality but idk tbh
I'm still dealing with this issue, even using the installer didn't provide these for me and the hub download still just doesn't work, the blue bar looks finished but it never actually does and the files aren't showing up in the explorer, really not sure what to do here
hi, i have a problem, can someone help me?
i have a shooter test, so when i shoot to some place, the bullet go to the bullet hole and if after that i shoot to another place without an obstacle, the bullet go to the last bullet hole, i have an video of that error if someone needs it
And if apart from that you could help me fix that when I start the game, the camera doesn't look down, it would also help me a lot
it appears to work now.. soo I guess you don't need to regenerate it each time! 🙂
this gives me object reference error on line 67, not sure why (it's the last line)
Last time I was messing with it it didn't work so much...
And which line is 67?
the last one (with code)
this are the codes
I'm assuming your error was a null reference exception error? @eager wolf
yes
So db was null and an error was thrown because that line attempted to call the get item method from a null. Apparently the resource doesn't exist.
yep, i'm an idiot, thanks
(called the folder "Ressources" not "Resources")
!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.
oh, sorry
All good. Just can't read it without downloading as it is

