#š»ācode-beginner
1 messages Ā· Page 305 of 1
if they're already in the list you don't need to detect them, other way around
(assuming you already dragged them in the inspector to list)
yeah i did
ok so enemies need to know about that script containing the list
so they can remove themselves on death
right, so in the enemy script it needs to find the other script?
yeah, store it in a variable so it can be done only once in awake
so on the start or so? and how do i go about storing it in a variable? im not entirely sure what's being stored exactly?
same way you stored List in a variable?
the script has the list, you have to store the script
thats the type for the var
so wait
i would put
it wouldnt be 'public script' ?
I really just dont get this stuff, I'm just not sure how to actually write this from nothing? im not sure what to really do going with this? idk
how come you pick making a game ?
if its a class have you not learned anything at all?
we've barely gone over a thing when it comes to coding in C#
it's all been just messing with stuff in the engine itself, making particle systems and materials and stuff
well coding is a whole different beast
we have barely gone over a thing about code, and i realized at the start of this semester i really dont have what it takes to figure out this stuff
and so thats why im trying to add just a little bit more to this
i just really dont understand most of this stuff and im getting kind of overwhelmed i guess
maybe start from the very basics and work your way back up instead of jumping into such complex tasks
i mean, i was going to add a loop because i thought it would seem a bit better, but at this point i dont mind just making a simple win screen?
its just the actual detecting whether or not the enemies are still there that ended up becoming more of an issue
its just that we're already sofar into the class so this stuff is due pretty soon
i've been messing with it for a while now, but decided to try and get a bit of help, since i don't know anybody personally that uses unity either
i don't see the point of these classes if you're not learning anything
fumbling and guessing your way around wont work in code, you need to be exact
well it won't as suggested already the method that does return you an Array will only tell you how many current enemies are there, it would never be null in the actual entry
yeah i wish we did more actual coding stuff, but idk what to do about it now
you only need to mainly get hang of referencing and using the basic types / functions
right, so im not sure a way to actually detect that, the array idea wasn't working, but i might've just not been using it right?
i just dont really have much time for this, since i also have other classes to deal with at the same time, and i dont have that much longer before this stuff is due
nah using an array in the first place was wrong way hence why my suggestion of a list
but yea explaining it will probably just go over your head unless you grab the basics, like how to work with a list (removing and adding entries etc..)
right, so im not sure how to actually get the list to recognize when the enemies are being destroyed, and then i guess maybe if i can get that, then having an if the list has nothing in it, then it can do that?
its not that much to do if you break it down into smaller steps. moving onto the next only when you understood what you did the previous one
List is useful because as you Kill off an enemy , you can modify lists to Shrink in this case. this gives you sort of a count down
couldn't you use a gameobject as a container for the enemies and when you Destroy them they get removed from the gameobject
thats the idea..
i just got here, mb.
but the current script that contains list of enemies is in another script and they're confused on why they need refrences to it
which script would this go into? wouldnt i need to add a way for it to recognize the enemies being destroyed before making a thing for it to shrink?
i see
You only need 2 Scripts.
lets say the first script is called EnemeyCounter/Manager
another is the Enemy script Itself
it's not a good practice to use a List<GameObject> unless you really need to
better to have direct references to the Enemy in the list
uh what
well yeah its good practice
if its a Component it already has a .gameObject property and a .transform
im confused why that's aimed at me
dunno lol
right, i have a script for enemyLooping (with the List and the function to reload the scene)
and then i have the enemyManager right now that's empty currently
correct, enemyLoop becomes enemyManager because enemyLooping makes no sense
or well, enemyLoop is the name of the file, uhh
keep name of file and classes the same or unity will throw a fit
yeah theyre the same
the class is enemyloop and the file is enemyloop
this is what that one has
and then the enemyManager is empty right now
yes just needs a public method that it can receive the GameObject enemy to remove
so it needs a public void? how would i go about having it receive the GameObject enemy?
well you can pass objects through parameters inside methods
as long as you declare it
so i would make a public void and call it
idk
enemydetect? or something like that? and it would have a parameter, but how would i get the parameter? im not sure
you're jumping ahead too much, first declare the method . Do you know how to write a method?
but inside () you declare what type of data this method can receive , in this case can either be GameObject or whatev your enemy script is (since this is what needs to remove from list)
so just saying GameObject? or would it need to be the actual list itself?
i have implemented a recoil animation and when i am out of bullets the animation still plays. Can anyone help?
yes, dont play the animation when you have no bullets
how? im very new to unity and dont really know
you'll have to share code so we know how you are even playing the animation in the first place
this has nothing to do with Unity. It's a question of logic.
If (NumberOfBullets > 0) play animation
there is no animation in that script
is this chat gpt code?
yes some of it
so any ideas?
got it
do you know basics of c# or/and unity?
if not i'd start with that instead of blidnly copy&pasting chatgpt generated code
without understanding it
that sounds more like a user error rather than it not working
right now your scripts have no relation. think about it logically, you have logic for when you are able to shoot. the animation should be done from there. Follow this to learn how to reference another script https://unity.huh.how/references
Right now your animation is completely unrelated to the shooting. Both just happen to exist at the same time
alr ill try that
you are already referencing another script also in RecoilScript, which i assume chatgpt wrote for you.
you should cache that value, because you dont need to get it every single time its done. get it once and store it
lmao
basically your Shooting script needs to be able to manipulate the canPlayRecoil bool
is your IDE configured? let's start with that
yeah it is
weird question but let say i got two of these objects
Class Object1 : MainObject, Interface1 {}
Class Object2 : MainObject, Interface2 {}
what would happen if i did
MainObject a; //(derived from Object1)
public void ChangeObject(MainObject b){
a = b
}
//(b is derived from Object2)
will the interfaces remain intact
or will everything be replaced
the object reference a will be replaced with the object reference b, but the interface implementations will remain intact @rocky gulch
Hi. I have a question: I have a variable by component, let's say light. I want to create a local variable: "GameObject", which will be equal to the light variable, but you cannot assign a GameObject via a component variable. How do I access the object that has this component? An example of what I want:
Hi = light.gameObject
Thanks
public interface IProgress<T> where T : ScriptableObject
{
}
Is there a better way to force implementations to be SOs? Because with this, I don't use T, which gives warnings
You can really limit what implements an interface afaik.
You could use an abstract SO as a base class though
Instead of an interface
No, sorry if I phrased it weirdly. Consider this:
public class BountyHuntGameSubtaskProgress : IProgress<BountyHuntGameSubtask_SO>
{
private readonly BountyHuntGameSubtask_SO _referencedSubtask;
public BountyHuntGameSubtaskProgress(BountyHuntGameSubtask_SO referencedSubtask)
{
_referencedSubtask = referencedSubtask;
Progress = new(referencedSubtask.SpaceshipTypesToHunt);
}
public Dictionary<SpaceshipType, int> Progress { get; }
public BountyHuntGameSubtask_SO GetReference() => _referencedSubtask;
}
I use the interface as a wrapper class for tracking progress of ScriptableObjects
I managed to circumvent the warning by introducing the generic GetReference() method
public interface IProgress<out T> where T : ScriptableObject
{
public T GetReference();
}
Interesting. Didn't know about the generic out params
Just a note about this. Since you are using MainObject here as the type, you only have access to variables or methods associated with MainObject, not Object1 or 2. This would mean you wouldnt be able to use stuff from the interface, unless you cast or Object1 or 2 override a method while using the interface as it wants
public class MovementController : MonoBehaviour
{
public Rigidbody player;
public float speed;
public void Move(Vector3 movement)
{
player.AddForce(movement * speed);
}
Is addForce not applied on the rigidbody? I'm trying to not let the player walk through walls, tried to fix that cuz i used transform. and i believe tahts the wrong function to use, so now I use Addforce. But now it wont move at all.
how do you call move
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
movementController.Move(movement * Time.deltaTime);
}
btw rigidbody should be moved in fixedupdate
addforce is using mass, so also there is that
check ur rb settings, how much is ur speed set?
also you should not be using deltaTime in that scenario
yea prob holding it back too rn
I tried seting it between 5 till 5000. no difference yet. I removed deltaTime, and turned the method into FixedUpdate. No movement yet :c
It stopped working after I changed the type of GameObject to Rigidbody since I wanted to use 'AddForce'. Could that be it?
is rigidbody falling ? can you show rigidbody setting
kinematic = not affected by forces
Oh. now it shot me forward yea. But I fall through the ground/plane if thats unchecked.
probably because collider isTrigger
yes, your collider is a trigger
did you do any research at all before using this stuff?
Hello guys, I'm trying to share my project on github. But I realise that when I build my project, I can't see the source codes in the files. So basically whenever I upload it to github, people cannot see what kind of codes I wrote it for the project. Am I missing something? I'm really confused to fix that problem.
which problem? you uploaded the build
the source code is inside the dlls
if you want to share a git project you need to make a repo from the project folder itself
How can I do this?
I'm confused, so you are saying that if someone would try to take a look at this project. They can see the codes that I wrote right?
any game that has a dll thats part of the code yes, any executable can be pretty much peeked at
most people who can do it probably wont care about your source code lol
I'm just doing this for portfolio, so I just want other people can see the scripts that I wrote for the project. It's all deal
if you want the project itself , you would need to commit the project folder where the Asset folder is
if its a portfolio should probably learn the how to make repos
Ahh all right, so I shouldn't upload the build. I should upload the main folder. Okay it's make in sense now
All right, I'll check it
NullReferenceException: Object reference not set to an instance of an object Player.FixedUpdate () (at Assets/Player.cs:30)
whats this error i only get it once when starting game
then when i start it again it goes
so i cannt build the game cuz ofthis error
null reference would probably not prevent a build
oh
im trying to stop the recoil animation when i have no bullets and its not working
thats the only thing that can be null yes the others are value types
raw still returns a float
i removed float still same error
float aint the error buddy
assign in awake
yeah done
it still errors ?
Is anyone available for this?
even the build works :D
ah.... well that sucks
that's what you have when using chat gpt code
well my intention was to just change the variables
so im assuming just list of object1 and object2 then using cast to change the values
Is the āBullets Depletedā thing getting logged?
Wait, this is chat gpt code?
check and log if canPlayRecoil is false . . .
Out of curiosity, why is it that some variables have to be set in Start() or a method and some can be set in a class outside of any methods?
such as?
The only things you can set in a field initializer are compile time constants
If it's not a compile time constant you can't set it in a field initializer
it's not just compile time constants, it is anything that can be accessed within a static context
unity does have some exceptions to this, for example you cannot access Application.persistentDataPath in a field initializer for . . . some reason (at least not on a scriptable object)
The field initializer is the area in a class outside of any methods right?
debug fillAmount
or check the UI anchors
also you can just ues dotween, would be simplier in your case with the OnComplete() method so you can handle the crafting
the crafting works
its just the bar
didin't say it doesnt
it stops at 0.9
A field initializer is when you use = something in the same line as a field declaration
Fields are the class-scoped variables declared inside a class but outside any methods
So if I make the field public int m and set it to 10, would it look like this in a field initializer? public int m = 10
Iām confused cause you said I can only set compile time constants in a field initializer, but I didnāt put the const there yet it still works
the integer literal 10 is a compile time constant
Ohhhh, so I can only set it equal to a compile time constant
well no, you can use anything that can be accessed in a static context inside of a field initializer. this is why you can call an object's constructor in there or access a static field. unity just happens to have a few restrictions of its own for some of its own static properties and methods
how do i make it fill according to the craft time?
Does someone know why my raycats wont hit when behind ?
you aren't using a layermask so it's possible that you are hitting the player with the linecast (and you only ever print when it hits something other than the object tagged as Player). also you should be using the CompareTag method rather than string equality when checking an object's tag
Alright, so last night, I was instantiating a Color in a field initializer, looked something like this:
public Color myColor = new Color(1, 1, 0);, but myColor wouldnāt work unless I set the value in Start(). Thatās a unity restriction, right?
no, that would work just fine. however it is also serialized so the value assigned in the inspector would be what is used. but assigning inside of Start would overwrite that serialized value
Ah, I see, thanks
i checked and when the camera is below the floor the hit is still player and not Untagged so thats the Linecast fault i guess ?
Hi Guys, Do you use GitHub version control (or any other) for your games' data?
ofc
But does it have sense to do that for small projects also?
Makes more sense than for big projects honestly. A small project might actually fit in the amount of LFS you get with the free tier
people divide into 2 groups:
- those who make backup
- those who will be making backup
Thank you guys. It's always very usefull to consult suff with more expirienced
How can i stop the two players from pushing each other by just walking?
This is the beginner coding channel. If it's not related to code, you might get better suggestions from #š»āunity-talk
pretty sure its related to code
(tbh, it looks like you've forgotten to set the physics matrix to avoid collision between characters)
Maybe show the relevant code
Nah i need them to collide, but not push each other away
set the player to kinematic when not moving
If you walk into something which cannot be pushed, like a brick wall, what happens to your velocity?
We don't know anything about what they're doing.
Other than not wanting the characters to push each other but needing them to collide
Its simple, at least i think so
- The players should act as walls to each other, not passing through, not pushing it away
- but also my "push" feature which i intentionally added should push the players away with a specific key
So basically i want the pushing to only happen when that key is pressed, and other than that it shouldnt normally push them away while just walking like how it is now
i tried setting the mass to very high, but both of them need to be high mass then, which then just makes it pointless, and then i couldnt jump also
https://gdl.space/filutibaye.cpp
Can someone help me out please. I am trying to make my ship to roll to 90 degrees when the button is pressed. The button is working, but the ship doesn't want to roll to the desired angle.
if you answer my question you have your solution
i would answer it if i understood it
but simply im very dumb
do you not know what velocity is?
not really
then you cannot be helped. you need to learn at least some very basic physics
Maybe show us the logs?
or maybe you can tell me the answer yourself, and i'll keep gaining knowledge slowly
This is when I press Q (tilt to the left)
or maybe you can just google what is Velocity and gain knowledge this way?
if you want to make physics based operations, then you'd obviously need some basic physics knowledge
i tried š¤·āāļø
yes i read this
then if you dont understand what is velocity from google
what are the chances you'd understand it from someone else
Are the logs fine? If so, you ought to be rotating towards the target as long as you're tilting.
then let me have the answer without the riddle pleaseš¢
there is no riddle lol
So what's your best guess as to what velocity is after reading that
you dont need to understand all the formulas
speed of objects?
Yeah there you go
good enough, so what is your answer to my question?
yeah i dont understand how that fixes my game problem
velocity gown down
goes
goes down to what ?
zero
hey how exactly do we tell if we have beginner, general, or advanced issues?
Are YOU a beginner?
Yeah
it suddenly started to work. idk what happened, but thanks anyway
exactly, so when your 2 players collide, to stop them pushing set their velocity to zero
Then go with beginner
fair enough
hey how do i get the console errors to display on multiple lines?
or just all console messages
like the log entry works for more information but long messages still overflow sideways
So I have to maximize the console to see the whole message
just click the log and look at the stack trace window at the bottom of the console window
you don't have to make your console even larger just to see that info
i have a code that says when i click the "E" button, to set the object to be a child of the camera. it works, but i have to click the "E" key about 500 times for it to do anything what am i doing wrong?
sounds like you are using GetKeyDown inside of FixedUpdate
of course you haven't bothered showing code so that is only a guess
lemme share the code
this? tried this in a bunch of ways, no luck
code
I didn't even realize it displayed down there
thanks
can't you use AddForce or something on rigidbodies
GetKeyDown is only true for a single frame when you press the key. this isn't necessarily a FixedUpdate/Physics frame. so using that in OnTriggerEnter is not going to work the way you want
And where did you put that?
i recommend looking into using a raycast or physics query to determine whether an object can be picked up instead of relying on physics messages
okay, i had it set to Just GetKey before and it did the same thing
In a OnCollisionEnter2D method
because OnTriggerEnter only happens for the first frame that the trigger is entered
#š»ācode-beginner message
hm, so how do i make it every frame?
best bet, make a bool, set to true in Enter and False In Exit. In FixedUpdate check the bool, if true set velocity to zero
is it possible to just relight one area of the map not the entire scene?
There really isn't a way to measure but imo if you're simply exploring the language, api or are having difficulties understanding a certain error/unwanted-behavior like syntax errors, null reference exception errors, improper type conversion errors and whatnot.. Unity beginner code should be fine. General coding issues with Unity would be imo more about standard issues like exploring design patterns, generic constraints/limitations, how data should be managed and anything revolving more design and less "help me get started" or "what's wrong with what I've got given X". Where they both overlap would be with reading/tutorial suggestions as the level of complexity these suggestions provide can vary tremendously. As for advance, it's likely for those who want to have discussions on something they've learned elsewhere and how they could integrate/implement these very specific systems with Unity - a difficult, large or tedious task for an individual does not necessarily make it an advance topic. Expect more criticism inside general/advance and hopefully less traffic (questions and responses). Just stick with beginner code if you've got simple problems or are wanting to provide less complex solutions. General and advance code if you're wanting longer discussions. This is all voluntary so don't expect any personal tutoring.
guys how can i set animator other animations?
Hello, everyone! I have a question regarding ground detection.
I'm currently working on a rigid body based character controller and, so far, I checked if the player character is grounded by using the CheckSphere method but it doesn't behave exactly the way I want it to. I have been looking for solutions on the internet and most people say I should be using a raycast or spherecast. Since raycasts cannot handle situations when the character is walking over very small gaps between two platforms, I believe using a spherecast is the way to go.
My question is:
Would using the Spherecast method in order to check if the player character is grounded make for a good solution or is it too expensive?
Also, if you know a more clever way and are inclined to share, please do so. :)))
public GameObject character;
void Start()
{
character.GetComponent<Animator>().Play("MyAnimation");
}
or something like that
I know
But it should assign
Mismatch
then change the types
your using the Old Text, you should be using TextMeshPro
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class addScore : MonoBehaviour
{
public TMP_Text text;
public addScore addscore;
// Start is called before the first frame update
private void OnTriggerEnter2D(Collider2D collision)
{
Score.score++;
text.text = Score.score.ToString();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
this code doesnt magically reference your desired references
you have to do it your self
drag and drop them in the editor
I see no references set
@wraith valley your using the Old Text, you should be using TextMeshPro
thats not the issue
it literally is
and where do you see that?
you see a null ref error and thats what youre worried about???
its null because he cant reference it
where has he said that?
here
that is not a reference, that is a declaration. references are set in the inspector which says NONE
what are you dragging into here
My text and script addScore
you've dragged in nothing
show the text
the exact thing your dragging
I did that
Are you dragging this onto a prefab?
Yes
You cannot do that
Prefabs cannot reference scene objects
where, you have not shown it
This
I should create prefab with text?
i did this and now all my textures are stuck on that after play mode, how do i fix? i just want it to scroll a texture but it appears to have scrolled every texture
void Update()
{
_image.material.mainTextureOffset += speed * Time.deltaTime;
}
With prefab
Maybe clone the shared material in Start and assign this material to this individual object. Then offset this individual material.
how can i clone?
Reminder that if you decide to prematurely destroy the object, you ought to destroy the material as well - loading a new scene will automatically do this for you though.
can someone tell me how to acces another variable from another script
or google "how to access variable from another script unity"
Maybe something like image.material = new Material(image.material);
Writing this from memory.
!code using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject gameOverScreen;
public float highScore;
public Text hightScoreText;
public float score;
public PipeMiddleScript piper;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void globalHighScore()
{
piper.high = score;
}
public void gameOver()
{
gameOverScreen.SetActive(true);
if (score > highScore)
{
highScore = score;
PlayerPrefs.SetInt("highScore", (int)score);
hightScoreText.text = "High Score: " + highScore.ToString();
}
}
}
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
public class PipeMiddleScript : MonoBehaviour
{
public LogicScript logic;
public AudioSource sound;
public float high = 0;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
high = high + 1;
logic.addScore(1);
sound.Play();
}
}
}
why my score var don't work
I don't see you assign anything to score anywhere
Likely you are getting confused by having playerScore and score
Then assigning to playerScore but trying to USE score
I want to make when you go touch the collider the score get higher
public OtherScript os;
public void Start()
{
os.myvar = 10;
}
ok
Ok, well i explained your issue
Thanks for the breakdown!
Thx now my code works
hey if I instantiate an object based on a prefab, and that prefab has a script, and that script contains a variable containing a script such as a CoordinateSystem cs = new CoordinateSystem(), can I access that Coordinatesystem in the line after instantiating the object?
sure why not
because I'm getting a nullreference and wanted to make sure it wasn't just bad timing
Yes, Instantiate() returns the specific instance of the object you instantiated
yes, if you reference it properly
called it
You'd have to show your code
Reference that and then use get component to access the variable
you don't need GetComponent
Heres the code, so far
PieceSetup:
https://gdl.space/raquyurote.cs
ChessPiece:
https://gdl.space/wokidogala.cs
BoardCoord:
https://gdl.space/noborilufu.cs
PieceSetup has an error on 122
hello. i have a rhythm game i am working on. i am having a specific issue with a lag spike that happens when i hit the first note, and then never again. looking at the profiler it seems to do some huge reallocation at that time for some reason. what could this be?
ā¦how
Heās instantiating a prefab
And it has a component
That means the prefab you instantiated doesn't have the ChessPiece script attached to it
And he wants to get a variable in that component
Praetor knows what they're talking about lol
hi, i am using netcode for gameobjects and i am trying to make a health system where if your health is 0 you die. i have an interface which has a damage method, and in my gun i have a raycast and when you click it invokes the method and damages the player. in the player i check if the health is equal to or less han 0 and destroy it. how would i go about making the server destroy the player because right now if the client kills the host i get the error [Netcode-Server Sender=1] [Invalid Destroy][Player(Clone)][NetworkObjectId:1] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.
[SerializeField] ChessPiece prefab;
void SpawnPiece() {
ChessPiece instance = Instantiate(prefab);
var whatever = instance.whatever;
}``` @thorn holly
no GetComponent required
thank you, my king script was the only one extending chesspiece, I need to fix the others
Why var if i can write gameObject type?
We don't want GameObject type
I used var because whatever is a placeholder example variable and we have no idea what type it is
it's just an example
Ok
Anyway why would we want "GameObject" anywhere in here?
Oh, so the Instantiate will automatically return the ChessPiece component attatched to the prefab?
yes
I did not know that was a feature
it also guarantees that you can only reference an object that actually has ChessPiece on it
I learned something new today
which would have saved this person from this problem
it's in the documentation
I was instantiating pieces that were meant to have a chesspiece on them, I just had
public class Queen : MonoBehavior
instead of
public class Queen : ChessPiece
I fixed it
Switching to directly referencing ChessPiece instead of GameObject for your prefab reference would make your code cleaner and avoid this mistake in the future
Can you do that for any component?
uh, sure?
how do i prevent my player from sticking to the side of a wall if a force is being added in the walls direction
Hi Guys, How do i repair/ prepare my audio file to fit in audio source? Cause when i downloaded my sound from yt it didn't work
ive added a physics material but that only works when the player isnt waling into the wall
where are you trying to "fit" it in?
Cool
what does this mean?
a physic material should be all you need
maybe I used wrong word, but I simply can't put my audio file in audiosource component
If I directly reference ChessPiece, can I instantiate a child script like King or Queen?
where are you putting it?
yes
and where is your audio file
What is ```rb.velocity = new Vector2(moveInput * speed * Time.deltaTime, rb.velocity.y);
I mean XD dunno if i understood
and is it any of these formats listed in here?
https://docs.unity3d.com/Manual/class-AudioClip.html
Poorly written code.
Why rb.velocity.y is there?
to preserve the existing velocity on the y axis
i added a physics material with no friction but if the player is walking into the wall he is stuck to it
Left and right?
y axis is up and down
so this is an issue with your movement script
yup, tried mp3 and wav but its converted so maybe it can cause problem
Why? If he only wants to move left and right?
yeah i was wondering how to avoid the issue
Why is the y axis up and down? Because that's how Unity is designed
and most coordinate systems
No
by changing your movement script?
Why save y speed if he uses x speed?
that's weird. what happens when you drag the file into the audioclip slot?
Precisely because we don't want to change y speed. So we use the existing y speed.
if you put 0 there, you would change y speed to 0.
Am I instantiating wrong?
You didn't change your variable type for piecePrefab to ChessPiece
Ok, thanks
nothing XD Literally nothing. I faced this problem once but forgor how i solved that
thanks, this is awesome!
anyway you definitely want to delete Time.deltaTime from there
it's wrong
sorry, not sure what's wrong then
maybe show a video of you dragging the file to the slot
one question: how do I get the instantiate to create the prefab object? Like I have a King prefab, with a King : ChessPiece script.
Do I want to instantiate the prefab separately and attach it once it's instantiated?
I don't understand the question
Instantiate creates everything
there's nothing to attach
it's already attached
attach it to what?
Instantiate will:
- Clone the entire prefab
- Return the reference to the ChessPiece script attached to the new clone
It won't let me create the object prefab, because it's not a chesspiece
nah, that wouldn't be useful. It's prolly sth with inappropriate converting.
if the prefab has a ChessPiece script or any script that derives from ChessPiece on it, you will be able to reference the prefab
I' m still being dumb thank you
Hey, I've tried using https://docs.unity3d.com/Manual/WheelColliderTutorial.html and i fixed a few errors but now it just says foreach statement cannot operate on variables of type 'WheelControl' because 'WheelControl' does not contain a public instance or extension definition for 'GetEnumerator' and i don't really know what to do
I still haven't fixed the : Monobehavior on the scripts
Sounds like you defined your wheels variable improperly
it should be WheelControl[] but you just wrote WheelControl
how to save the highest score
save to file, or use playerprefs for now just to learn
if(currentScore > highestScore) Save()
you load it?
but how do I load it at the begin of the game
put it in a function thats runs in beginning of game
Hey does anyone know how to instantly drag a game objects after spawning it?
(I have a button that spawns a game object on the mouse when you press it. I want it to spawn and then instantly drag it without letting go of the left mouse button and then despawn when you let go of the mouse button. So that pressing the button and dragging the object is one smooth motion.)
sounds like you would just:
- in StartDrag spawn the thing
- in drag, drag the spawned thing
- in EndDrag despawn the spawned thing
where would i put start drag than because i still want the button to spawn the game object š
You'd put IBeginDragHandler on whatever you're clicking to start the drag process.
!code using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEditor;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject gameOverScreen;
public float highScore;
public Text hightScoreText;
public float score;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
void Start()
{
if (PlayerPrefs.HasKey("highScore"))
{
highScore = PlayerPrefs.GetInt("highScore");
}
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
gameOverScreen.SetActive(true);
if (score > highScore)
{
highScore = score;
PlayerPrefs.SetInt("highScore", (int)score);
PlayerPrefs.Save();
hightScoreText.text = "High Score: " + highScore.ToString();
}
}
}
Can sommone tell me how to make that the highscore is actually changed because it doesn't work
š 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 the links in the bot below to send code properly
are you sure the script is running also where are you increasing score?
add Update method
yes the code is running but it overwrite the highscore function by 0
you don't actually display the high score until you save it in the gameOver method
you're only ever setting the high score text in GameOver
as pointed out score text only updates on death, make an Increase score method change text there
ok
I have a couple of respawn points that have the same animation that if the player collides, it plays a animation, but it resets the copies of the respawn point to the same point as the first respawn, how can i fix this?
you're probably animating the transforms?
esp if they share the same animation you will have problem , make sure it only moves local
unity tutorial, again (it broke my wheels)
yea im making them scale a bit yes
how would i make it local?
not. code question, also is the model thats messed up
it doesn't work
it will just spawn the object but wont instantly drag it (without letting go of the button and clicking on it again)
you'd have to show what you tried
forgot how to do it with animator , did you make sure root motion its unchecked ?
umm i think it's this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WheelControl : MonoBehaviour
{
public Transform wheelModel;
[HideInInspector] public WheelCollider WheelCollider;
// Create properties for the CarControl script
// (You should enable/disable these via the
// Editor Inspector window)
public bool steerable;
public bool motorized;
Vector3 position;
Quaternion rotation;
// Start is called before the first frame update
private void Start()
{
WheelCollider = GetComponent<WheelCollider>();
}
// Update is called once per frame
void Update()
{
// Get the Wheel collider's world pose values and
// use them to set the wheel model's position and rotation
WheelCollider.GetWorldPose(out position, out rotation);
wheelModel.transform.position = position;
wheelModel.transform.rotation = rotation;
}
}
i'm expecting something like (pseudocode):
Transform placeholder;
void OnStartDrag() {
placeHolder = Instantiate(prefab);
}
void OnDrag() {
placeHodler.position = mousePosition;
}
void ONEndDrag() {
Destroy(placeHolder.gameObnject);
}```
so fix the model
how do i
first check the pivot gizmos to make sure they are the correct direction
It works thx
I made a function which generates a mesh for a 2D chunk in my game so that I can render it with Graphics.DrawMesh, how do I give each tile on the chunk its own texture
yeah it works but high score text still not changing when you surpass score until death
it change when we click on Play Again
thats how you want it ?
Currently my entire mesh is using a single sprite, but how do I make each tile able to have its own sprite
just asking myself what are these weird noses in the video
my model is ok i guess
i tried it like this
!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.
wdym "just ok" that tells me nothing about the gizmos
You ignored the result of Instantiate
so I don't know how you expect to move the instantiated thing if you're not even keeping a reference to it
Your ide is not configured
!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
how do i know everything is ok with gizmos?
that too
i'm like rlly new to unity
you look at the them with your eyes, making sure they match the wheel collider
like these?
are those gizmos in Local or global mode
i think local
idk how to check
don't think, be sure
You duplicated a script
OH i have three of them
ye it's local
Yeah, that would be an issue
Can only have one
In the same namespace*
by locking it front view, left view, top view etc
Back in Time babyyy
or the license plate iirc was "OuttaTime"
hehe, itch assets ftw
I changed the script now the high score will show before death
cant say that, its just a futuristic delorean maybe not even delorean..
we can call it a stainless steel coupe
steel body is the key to the disperse of flux....
"ToSpawn" is the object that gets spawned if you mean that
or i changed transform.position to obj.position if you ment that
i am a bit confused tbh
ToSpawn is the prefab
the actual object that gets spawned is returned by Instantiate
you're ignoring that
var thing = Instantiate
Always look at the docs when confused
And that spawned thing is the very thing you need to be moving
so it's hard to move that thing when you're not even storing a reference to it
until the nueralink plugin
how can i do that with an object that dosent exist yet š (sorry i dont think i ever needed to do something like that before)
what do you mean doesn't exist yet?
As I said, Instantiate returns it
I just showed you
ohhh i completely overlooked that sorry :')
how do i make a gameobject that has a script attached that has values that can change and can be accesed and changed from anywhere in the current scene and other scenes
That describes any variable on any script basically
make a script, put a variable on it
put the script on an object
Can someone help? I have a function which generates a mesh for a chunk in my 2D world, but currently all of the tiles that are inside the chunk are drawn with the same sprite. How do I make it use multiple sprites?
The mesh is drawn using Graphics.DrawMesh
Why not use a TIleMap?
you would have to UV-map the mesh then
TileMaps wouldn't work with my current tile system
each tile in my system has a list of 'Elements' which are basically what make up the tile
a floor, a wall, a roof, an item.
that sounds more like an internal data structure thing than a Rendering thing
for rendering you could use a Tilemap
you could use multiple tilemaps - one for each layer of stacking
can i make this:
wheelModel.transform.rotation = rotation;
but with only one axis?
what's the axis?
Yeah but I thought it would be more performant to program something that is more suited to my data structure
x axis
unity has a wheel collider example, why are you guessing your way around it lol
Wouldn't you need some custom shader to do this sprite stacking with a MeshRenderer anyway?
How can I restrict this from adding all the contents of triviaJson.text into triviaDatabase?
JsonUtility.FromJsonOverwrite(triviaJson.text, triviaDatabase);
triviaJson.text has 547 questions , triviaDatabase is a list to hold the data , I wanna clear the list on start with list.clear() then refil the list with a specific number of questions from triviaJson.text
no I basically planned to create several planes above each other :[
for each stack
project the forward direction of the object in question on a plane with the x axis as the normal, and use that with Quaternion.LookRotation to produce the new rotation
if it is needed for that specific tile
This sounds functionally identical to a bunch of Tilemaps except for the part where you have to do manual UV-mapping which is annoying
not sure what you're asking here, wdym restrict it from adding all?
Ok fine
should I have a separate tile map for every single chunk or one for the entire map
sounds like you probably want a tilemap for each chunk and each layer
correct , I want to only add x questions not all
it kinda depends on whether tilemaps already do performance things like culling tiles that aren't visible right now
if it doesn't I'd probably have to create a tilemap stack for each chunk
of course
Sounds like you want an "All questions" object you load from JSON and then pull a random sampling into a separate "Current questions" object
You would have to specify that criteria somehow though, what would distingush those x questions from others
Then I believe it would be better and more performant to have a single stack of tilemaps for the entire map
I'mtrying to use a for loop
for (int i = 0; i < triviaJson.text.Length; i++)
{
JsonUtility.FromJsonOverwrite(triviaJson.text, triviaDatabase);
}
so 3 tilemaps, assuming I have a floor layer, a middle layer, and a roof layer.
why not grab them into a list then work with lists instead, so you can do things like shuffling or linq.. etc..
Like add to a list then fill from that?
hey, im trying to make a leaderboard using google play services. To show the UI, im using Social.ShowLeaderboardUI();, but it doesn't work. I have to use another code or something? Thanks!
unless I decide to allow players to create multifloored buildings
i think i know what the issue might be
oh wow lets see
Like have a list containing all possible questions and then a different list containing the ones you want
oh wow then lets not see
anyway where did you see this function to be used with leaderboard ?
well, i can search the web. Btw i used before PlayGamesPlatform.Instance.LeaderboardUI (i dont know if its exactly that code) and it worked, but i need to show more than one leaderboard so i cant use that i think
thats interesting...
i have faced a similar issue before
with the play store
really?? i dont know if i have to believe it sorry ahahhahah
yep, i think this issue really needs to be searched in depth, i would even say, with a magnifying glass
i agree
if you're not contributing anything helpful don't even bother
I was just looking at the package to find that method thats why, but it was in a different class called Social thats why I wondered where you saw that
seems to be related to Android
yeah probably, i found it yesterday, i dont have the page where i found it but now searching about leaderboards with google services, they use that line of code to show leaderboard
You're using the UGS one though right ?
what do you mean?
I meant this leaderboard
https://docs.unity.com/ugs/en-us/manual/leaderboards/manual/leaderboards
oh, im using the google play services leaderboards, i mean, i installed the package to install that services in unity and what things (the package im talking about https://github.com/playgameservices/play-games-plugin-for-unity/blob/master/current-build/GooglePlayGamesPlugin-0.11.01.unitypackage)
ohh yeah last time I used their plugins nothing would work lol I just used another solution with a better SDK
nothing saying thats the case though.
The other functions work ?
yeah it makes sense, btw this video shows more or less what i did, if its helpful: https://www.youtube.com/watch?v=lCZd_URHVK8
In this video, I show you how to set up your Google Play services so that you can add leaderboards to your Unity game!
Link to Play Games package: https://github.com/playgameservices/play-games-plugin-for-unity/tree/master/current-build
Download Mighty Mini Golf (for free!):
iOS: https://apps.apple.com/us/app/mighty-mini-golf/id1614873320
Andr...
show your current code
what do you mean, the other thing i tried??
did you make sure is running at all
like other functions, like saving the score etc.
or is it just UI not working
oh, well i was trying to fix that but without the ui working i cant check that really
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using TMPro;
public class playGamesManager : MonoBehaviour
{
//private const string leaderboardNormal = "CgkIm56s2cEQEAIQAQ";
//private const string leaderboardEasy = "CgkIm56s2cEQEAIQAg";
//private const string leaderboardHard = "CgkIm56s2cEQEAIQAw";
public static playGamesManager playgamesmanager;
public TextMeshProUGUI DetailsText;
public bool connectedToGooglePlay;
// Start is called before the first frame update
void Start()
{
SignIn();
}
public void SignIn()
{
PlayGamesPlatform.Instance.Authenticate(ProcessAuthentication);
}
internal void ProcessAuthentication(SignInStatus status)
{
if (status == SignInStatus.Success)
{
// Continue with Play Games Services
connectedToGooglePlay = true;
string name = PlayGamesPlatform.Instance.GetUserDisplayName();
string id = PlayGamesPlatform.Instance.GetUserId();
string ImgUrl = PlayGamesPlatform.Instance.GetUserImageUrl();
DetailsText.text = "Success \n " + name;
}
else
{
DetailsText.text = "Sign in Failed!!";
connectedToGooglePlay = false;
// Disable your integration with Play Games Services or show a login button
// to ask users to sign-in. Clicking it should call
// PlayGamesPlatform.Instance.ManuallyAuthenticate(ProcessAuthentication).
}
}
public void LeaderboardUpdate(bool success)
{
if (success) Debug.Log("Updated Leaderboard");
else Debug.Log("Unable to update Leaderboard");
}
public void ShowLeaderboard()
{
Social.ShowLeaderboardUI();
}
}
this is the code of the gameobject that manages the things about the google play services
yes so are the logs printing ?
and is text saying "success"
oh yeah, thats actually the signin function, that works yeah
with a button in the scene
i can try that
yeah it works actually
it calls the function
well since this seems to be play/android related, i'm gonna assume that function may need to run within the android enviroment
it probably uses native UI
docs just says to run that function
https://developer.android.com/games/pgs/unity/leaderboards
so nothing unusual
yeah, i think so, but i tried it on the phone and it doesnt work, its weird
yeah that page i meant
there is like two methods to do that, the second one is the one that works for me, but it only shows one leaderboard
ohh
so make the function for all of them
maybe because you have multiple ones it doesn't know which to open unless you specify
do you mean like separated ones??
yea
like
PlayGamesPlatform.Instance.ShowLeaderboardUI("1");
PlayGamesPlatform.Instance.ShowLeaderboardUI("2");
PlayGamesPlatform.Instance.ShowLeaderboardUI("3");
oh yeah but in the same function??
yup
isnt there a better way of doing it with like singletons or smth
yeah i should try that now that you say it
though not sure why youd want to show all three at once lol or even if it would work
i just remember someone saying there was a certain way that you should do what im trying to do a while ago
but i dont really now if it works
"Singleton" just describes a script for which there will only be one copy
Your question was just extremely vague
like you literally provided no details at all
SOunds like something a SaveGameManager or something like that should handle
it should live there
If you're asking how to get a reference to such a script, then sure the singleton pattern is one option
yeahl, the thing is in the docs says that the Social.Showleaderboard... shows "all leaderboards" and the PlayGamesPlatform.Instance... shows "one leaderboard" so, i dont know if the solution you gave me works like the Social.showleaderboard. You know what i mean?
But any technique of getting references will work. You just need a reference somehow.
https://unity.huh.how/references @amber spruce
alright thanks
yea I see what you mean..its strange then it wont open all at once.
yeah, and how i want to show the leaderboards all in a single button, i dont know if the PlayGamesPlatform... solution would work
true you'd have to handle your own UI for each
well, im going to try the solution you gave me, to see if it works, btw thanks a lot!!
sure thing, goodluck!
void generateTiles()
{
tiles = new List<TileThing>();
foreach (var element in elementRegister)
{
if (element.elementType == ElementType.Floor)
{
foreach (var sprite in element.floorElement.sprite.sprites)
{
UnityEngine.Tilemaps.Tile tile = (UnityEngine.Tilemaps.Tile)UnityEngine.Tilemaps.Tile.CreateInstance("Tile");
tile.sprite = sprite.sprite;
tile.name = "tile-" + element.id + "-" + sprite.material;
tiles.Add(new TileThing(element.id, sprite.material, Direction.South, tile));
}
}
}
}
I have this function that generates tiles at runtime
all the needed tile types for the game
but for some reason when I try to draw with the tile type using settile
it doesn't work
nothing happens
it only shows the first leaderboard in order of the code, and the scores dont work either, nice hahahah
hello, i created a function called invincibility in another script. i wanted to use it in other script. but when i am creating refernce, it can't recognize the name of the script.
`using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using Unity.VisualScripting;
using UnityEngine;
public class potionscript : MonoBehaviour
{
// Start is called before the first frame update
public BIRDSCRIPT BIRDSCRIPT;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
invincibility();
}
}
}
`
you probably shouldn't name the reference identical to the type
BIRDSCRIPT birdScript; would be a simple change to keep you and ur IDE from getting confused
Do conventions mean nothing to you?
anyway you haven't even explained what your issue is
if invincibility() is a method in ur BIRDSCRIPT
you just need to make sure its a public method.. and you can access it by using the script reference..
but when i am creating refernce, it can't recognize the name of the script.
What does this mean exactly?
like myBirdScriptReference.invincibility(); but im just guessing what u mean
i have tried that.
thats just a general rule.. regardless of ur question
šæ another reason I use Unity's leaderboard or lootlocker
https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity
oh neat, theres a Unity conventions page
yeah it makes a lot of sense
and = && is or || ?
|| is or
ty
== is equal to
hey guys i need quick help. i know there is a way how to separate reference groups in inspector by typing some stuff in script between groups of variables
can you remind me how is that done? saw it somewhere but forgot
thank you so much š
no problem, https://assetstore.unity.com/packages/tools/utilities/naughtyattributes-129996 also if you wanna get spicy with them
thanks bud, i just need simple separation, tho i will save this link in case i want to make it better š

Gues you can make an empty header then?
idk will test now, i just want to have title for different groups of references
it will make navigate through them lot easier
Yep
I can`t drag and drop
you can't drag and drop what where?
what do you mean by "my werewolf"
those .asset files? Why are they .asset files and not pngs or something?
I can`t drag and drop my werewolf to animation
where did you get those from
Werewolf?
the .asset files
From site
You can make a sprite sheet and set it as a child of the animator component
I did that
can you be more vague please?
Or if you drag a sprite sheet into the scene view, it automatically creates an animation
Yo guys, does the OnCollisionStay2D act like an update function?
No
Update runs every frame
not even close
OnCollisionStay runs every physics simulation step while the collision is happening
closest would be fixedupdate
I created an animator and a file with animations, but in the file with animations I cannot attach my pictures that I divided into separate particles through the editor
that doesn't answer the question of where you got the .asset files from
and why you're not just using normal image files
or a spritesheet
yes those are sprite assets
it looks like you dragged them into the folder for some reason
don't do that
So if i said
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "DogEnemy")
{
health = health - 10f;
{
{
That would only run once?
drag them directly into the scrubsheet
it will run every physics simulation step while the collision is happening, as I said before
I don`t how
I dont get what that means ngl.
every time unity simulates physics (50 times per second by default), while the collision is happening
what part is confusing you?
Oh cool
You explained it now so i get it
Also you should rather use this
if (collision.gameObject.CompareTag("DogEnemy")) { ...; }
Why is compare tag better?
it's more performant because it doesn't allocated any managed C# memory which will need to be garbage collected later.
when you do .tag a new String object has to be allocated in managed memory
- Better performance for free
- If you pass in a string that isn't actually a tag, it'll warn you
Oh thats cool
Thanks
So, if you accidentally typed "Dogenemy", it'd tell you there's no such tag as "Dogenemy" and you could see that and be like "Ah, I mistyped it"
Do I have to use a hold interaction if I want to check if a button is held down? action.performed triggers only once, just like started
What are you trying to accomplish exactly? Also #š±ļøāinput-system
Oh didn't realize there is a specific channel, lets move there then
i cant figure out how to get my character to move as a first person view
it wont move with aswd
the PlayerMotor is this code: https://gdl.space/uveduqaxop.cpp
the InputManager is this code: https://gdl.space/amafemipet.cs
Are you getting any errors
nope
i was with the orginal code but i just took the code it suggested
i can send the orginal code
Are you sure? Look at the console when the game is running
interesting.. lol
Yeah that's a lot of problems.
lol
Top one: You have a script component on something with no scripts attached. Chances are it's related to the second: PlayerMotor is not a component. It should be in its own file and it should keep the : MonoBehaviour that a new script comes with
Third error is the second error again. Fourth error is that you've got a negative scaled object with a collider which won't break things but might behave incorrectly.
Fifth error is proably nothing to worry about at the moment but you might need to address if you want to use the debugger
Why does the werewolf fall?
gravity
lol
I have collider
Yes
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlackWerewolfController : MonoBehaviour
{
public float speed = 10;
public float jumpForce = 5;
public float h = 0;
private Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (h != null)
{
h = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(h, transform.position.y, transform.position.z) * speed * Time.deltaTime;
transform.position += movement;
if(h >= 0.1)
{
GetComponent<SpriteRenderer>().flipX = false;
}
if (h <= -0.1)
{
GetComponent<SpriteRenderer>().flipX = true;
}
}
}
}
ur collider looks like it may be inside the floor when it starts
lift it up above it some more and try again
i cant figure this out
Movement via transform.position is teleportation and will ignore all colliders
why this so hard lol
Transform.position y and z always 0
Until you get even a frame of displacement from gravity, then you're doubling your y position every frame while ignoring all colliders
How?
Because you're adding the Y and Z positions to the Y and Z positions every frame
If those are ever not zero, they're going to double every frame
They are 0
And since the rigidbody causes a change in position, you get a smidge of downward motion and your teleportation take it from there and wombo combo until infinite
At start probably
But look at the inspector while playing
Do they stay at 0, 0?
So then they're not at 0
exactly
i did it guys
I fixed that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlackWerewolfController : MonoBehaviour
{
public float speed = 10;
public float jumpForce = 5;
public float h = 0;
private Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (h != null)
{
h = Input.GetAxis("Horizontal");
Vector3 movement = Vector2.right * h * speed * Time.deltaTime;
transform.position += movement;
if(h >= 0.1)
{
GetComponent<SpriteRenderer>().flipX = false;
}
if (h <= -0.1)
{
GetComponent<SpriteRenderer>().flipX = true;
}
}
}
}
now i jsut need to figure out what i want to make the game about
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector3 player = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y);
}
}
}
The camera doesn`t follow
your code isn't doing anything other than storing some data in a variable and discarding it
šæ
respond with something helpful other than some emojis
Ok
to set position of something you need to get their transform then access the .position
I know
doesnt look like it? based of the code you are posting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
public GameObject camera;
// Start is called before the first frame update
void Start()
{
Vector3 camera = transform.position;
}
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector3 camera = new Vector3(player.transform.position.x, player.transform.position.y, player.transform.position.z);
}
}
}
you create 2 variables, you create a new local variable which you set to the position of the object with this script
thats just the first 3 lines of code
and it makes no sense
i dont need to comment on the rest
To set the position of something you need to get their transform and access the .position
I didn`t?
There`s ```cpp
player.transform.position.x
Right now here is what your code actually does:
In start, you make a local variable you never use that ceases to exist when the function ends.
In update, you make a local variable you never use that ceases to exist when the function ends.
That's it
are you guessing at what to write by chance? you should maybe start by following a tutorial or at least doing some c# basics
instead of creating a whole new vector and accessing the XYZ, you can just use .position which is a Vector3 already
If you want to set something's position, you need to actually, you know, set the object's position
you just happen to have a gameobject named camera, and at the same time a Vector3 named camera. These are both completely unrelated to each other
Yes, that is the current value of the player's X position. What are you actually doing with it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
public GameObject camera;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (player != null)
{
camera.transform.position = player.transform.position;
}
}
}
aye! that makes more sense
did you test the code? do you see any results
But i should erase the GameObject camera
yes you can do just transform.position if this script is on the Camera
well ur kinda using it
you also really shouldnt have a class named Camera, because unity has one as well
Assuming this script is on the camera, you can just use transform.position
but yes.. transform.position would be the same gameobject that the script Camera is attached to
Yes
I want to erase that
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector3 vector = new Vector3(player.position.x, player.position.y, -10);
transform.position = vector;
}
}
}
I need with -10
hey guys so im making a 2d platformer game and i got my 2d character movement from a video online and im able to move left and right but for some reason im unable to jump, can someone help me, this is my code :
You should definitely rename that class
Edit: ah, I see that was mentioned
which means, the camera needs to be behind all the other game objects so they can actually be visible infront of the camera
Start the video over. You did something wrong. Most likely something in the editor setup, not the code.
Becouse i did with vector3
probably nothing to do with the code, did you setup the ground layer correctly? maybe increase the 0.2f value a bit too
But thats doesnt work
You are setting y velocity to 0 every fixed update
idk what your saying tbh, but i was explaining why you need -10 and cant just set it to the same Z which would be 0
i used the debug log and it says that it's touching the ground :
Definitely this: #š»ācode-beginner message
double check your code vs the tutorial
im taking a beginner game design at school so dont know much lol how would i fix it
I'm not sure how the tutorial did it, but you need to just NOT set y velocity to 0
There are multiple ways to handle that
The tutorial would have had to handle it in some way
I know
Because i`m using vector3
But thats doesnt work
thx i just set it to rb.velocity.y and it works now
Good choice
yo i need some help i want to that i get damge wenn i collied to an "Enemy" but it dont work can someone look over my script?
How do I approach a jump? When you're only allowed to jump when youre on a ground surface? without having to use 'IsTrigger'? cuz then i fall through the ground. Do I make a second floor thats invisible that will be a trigger thats on the same location as the floor orsum?
Follow any basic movement tutorial, they will all cover how to do ground checks etc.
there are several viable approaches of course
I am, but this video is using a cooldown on a jump, which I thought is weird. But alr ill find a diff one
sure, show the code
just follow the tutorial and see how they handle the ground check
you can rewrite it later to remove the cooldown if you wish
the important part of a tutorial is understanding
You're not just supposed to copy it and get a working thing and turn your brain off
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public int maxHealth = 100;
private int currentHealth;
public Slider healthSlider; // Slider für die Healthbar
void Start()
{
currentHealth = maxHealth;
if (healthSlider == null)
{
Debug.LogError("HealthSlider not assigned!");
}
else
{
healthSlider.maxValue = maxHealth; // Setze den maximalen Wert des Sliders
UpdateHealthUI(); // Aktualisiere die Healthbar-Anzeige
}
}
void Update()
{
// Prüfe, ob die "H"-Taste gedrückt wurde, um Schaden zu nehmen
if (Input.GetKeyDown(KeyCode.H))
{
TakeDamage(10); // Füge dem Spieler 10 Schadenspunkte zu
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision detected"); // Debug-Log für die Kollisionserkennung
// Wenn der Spieler mit einem Objekt kollidiert, das den Namen "Enemy" hat
if (collision.gameObject.name == "Enemy")
{
Debug.Log("Enemy collision detected"); // Debug-Log für die Kollision mit dem "Enemy"-GameObject
// Füge dem Spieler Schaden zu
TakeDamage(10);
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
UpdateHealthUI(); // Aktualisiere die Healthbar-Anzeige
if (currentHealth <= 0)
{
Die();
}
}
void Die()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("GameOverScene");
}
void UpdateHealthUI()
{
if (healthSlider != null)
{
healthSlider.value = currentHealth; // Aktualisiere den Wert des Sliders basierend auf der aktuellen Gesundheit
}
else
{
Debug.LogWarning("HealthSlider not found for updating UI!");
}
}
}
good god my eyes
!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.
I don`t know
cs
But without GameObject doesn`t work
huh
whats wrong now?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
public GameObject camera;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector3 vector = new Vector3(player.position.x, player.position.y, -10);
camera.transform.position = vector;
// camera.transform.position = player.transform.position;
}
}
}
Without GameObject doesn`t work
is this script on the camera?
Yes
if it doesnt work then it probably isnt
show how your doing it without GameObject
click one of the links, and paste your code then send the link here, makes it easier to read code for us
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (player != null)
{
Vector3 vector = new Vector3(player.position.x, player.position.y, -10);
transform.position = vector;
// camera.transform.position = player.transform.position;
}
}
}
So what's the problem
Well... is this script attached to the camera, or to something else?
what doesnt work about it
That doesn't answer the question
The camera doesn`t follow
it should be at 0
Also why did you name your script Camera? That's a recipe for sadness
show it
At 0 i see anything
Screenshot above
run the game.. pause it... show the player transform..
and it's at -10
how does one make like a collection in code, if u have a lot of fields you wanna group, you can do like:
something
{
ur fields
}
what is that called?
and then show the camera transform
struct or class
why is the cmaera script attached to the werewolf
class is for a type of thing, i want jus tcollection so i think struct is the thing
the script isnt attatched to the camera
they are both for "type of thing"
The difference is whether it's a reference type or value type
lol, theres ur problem ^
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why have you just took this other guys code instead of showing your own? š¤
Thanks
wait
wut
š
my bad wait a sec
That`s mine
I don't get why there's an error here:
private void UpdateBountyHuntSubtasks(SpaceshipType defeatedShipType)
{
_selectedGameTaskProgress
.SubtaskProgress
.Where(subtaskProgress =>
subtaskProgress.GetScriptableObject() is BountyHuntGameSubtask_SO bountyHuntTask &&
bountyHuntTask.SpaceshipTypesToHunt.ContainsKey(defeatedShipType))
.Select(bountyHuntProgress => bountyHuntProgress as BountyHuntGameSubtaskProgress)
.ToList()
.ForEach(bountyHuntSubtaskProgress => bountyHuntSubtaskProgress.Progress.Values[defeatedShipType]++); // <--- ERROR HERE
}
Cannot apply indexing to an expression of type 'System.Collections.Generic.Dictionary<main.entity.Overworld.SpaceshipType,int>.ValueCollection'
Values can't be accessed by index like that
https://hastebin.com/share/davirerizo.csharp this should be the right one
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ValueCollection is not a list. It has no order. You can't get an element by index
and whats the problem again? i dont want to scroll all the way up
Hmmm. How do I just increment the value of the element at that key?
what are you trying to do here? This looks very convoluted
sry to bother again but i was wondering if any knew how or had a tutorial showing how to make a 2d sprite go up ladders or stairs since i need my sprite to do so and with my current movement controller it's unable to do so, for reference this is my current scene , and this is my movement controller script,
the collision withe the enemy will dont work i dont get damage
myDict[key] = myDict[key] + 1
aDictionary[someKey] = aDictionary[someKey] + 1;
assuming it's a key into the dictionary and not an index into a list
do you get either of these Debug.Logs for collision?
Ohhhh
.ForEach(bountyHuntSubtaskProgress => bountyHuntSubtaskProgress.Progress[defeatedShipType]++);, yeah that seems to work
At least the compiler is fine with it