#💻┃code-beginner
1 messages · Page 322 of 1
so its fine to rename
just if its a MB or SO make sure the filename matches as well as meta
Doing Ctrl+R+R on a class name, in VS, changes the file names with it
yeah same with rider
just mentioning since i have no clue what people use or if its properly setup
rider is pretty good for unity refactors, it will auto add needed attributes, and can even refactor stuff inside the scenes and asset and prefab files
Hello, i'm working on a project where at one point i need to be able to store and load different shapes for a polygon collider.
When my player switches from different states i need its hurtbox (a polygon collider) to change shape accordingly.
What would be your best solution to do it ?
do you already store them?
you are over complicating it, just have multiple colliders you turn on and off
Thank you very much!
how would you do that ?
make a object that has multiple colliders on child objects and turn those objects on and off in code as needed
way simpler then trying to modify collider at runtime
mesh collider
- change the mesh when needed
i'm working in 2D
i've just written this code but i feel like it is not the best way to disable / enable said child
it's called on each update
why would you do it on each update, instead of just when the target changes
would this work ?
i mean yes it will work but is it optimal ?
would worry just about making things work
but my point was something is setting target, so why not have the logic that sets target handle this isntead doing it in update
How can i only use everything in Update while my Player is alive so i don't get a error Message when it dies?
Code:
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Distance : MonoBehaviour
{
public Rigidbody2D rb2D;
public GameObject Player;
public Transform PlayerPosition;
public Transform Blackhole;
float distance;
private Vector3 Atraction;
public float Gravety = 1000;
void Start()
{
Player = GameObject.FindWithTag("Player");
PlayerPosition = Player.transform;
rb2D = Player.GetComponent<Rigidbody2D>();
}
void Update()
{
distance = Vector2.Distance(PlayerPosition.position, Blackhole.position);
//Debug.Log(distance);
Vector3 direction = Blackhole.position - PlayerPosition.position;
direction.Normalize();
//Debug.Log("Direction from object1 to object2: " + direction);
Atraction = (direction / (distance / 2)) * Gravety * Time.deltaTime;
rb2D.AddForce(Atraction);
}
}
just null check player at the start of Update and return early
if (Player == null) return;
Update on my enemy AI script: the issue with the different AI modes has been resolved (Update is now spelled correctly), but the speed issue still remains. Code: https://hastebin.com/share/ihunavowim.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!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.
Player character behind and in front of objects
Hey guys. What does it mean when yield return null lets say for example. Waits for next update? I do not seem to understand how updates work and I do not even know what to look for on the internet. Can anyone point me to the right direction so I can do some research?
Yes. Waits for the next frame (update)
This may help
https://docs.unity3d.com/Manual/ExecutionOrder.html
Yes you can think of that as "wait one frame"
Looks like it runs immediately after update does, interesting
So If I am getting 60 frames per seconds. It calls the update 60 times?
So what do you actually mean when it waits one frame?
Speaking about the yield return null
I mean the code on the next line doesn't run until the next frame
I mean it literally
Are you asking what a frame is?
does anyone know how to make record script?
example you survived 5 minutes and you get new record part (first image) and saves time
you survived like lower than 5 minutes you get your time (your time is the time you survived but you didn't get a record) and has best time the record you made
is that not it? does it not work or what
no my script only appears your time
so is this code and these images from your game that you wrote?
A frame is a loop, it contains everything that needs to happen in the game. (Simplified almost to being incorrect)
It is NOT a second or any specific amount of time
A frame is basically a still Image of your game. Every frame the game draws a new image on the screen. By drawing lots of images really quickly, the game appears to be animated
Same concept as a cartoon or TV show
All the stuff that needs to render and is written in update happens in a frame. The next frame will wait as long as necessary for the previous frame to complete
the first image is my version
second is from another person
can i send you dm to send you a video of the original game
im making a remake game
no dms, ok so that makes more sense now i know what im looking at
1st is your game, 2nd is game your trying to create
so is the code you sent your code? or from a tutorial or something
the new record image is mine (remake)
and the second is original game
is my own
So okay. But these should happen too fast to be able to play the game right? What matters if I wait for one frame or not since I would not notice any difference?
why is there 2 different floats in PlayerPrefs? why not just have 1 "best time"
I don't understand what you are asking.
Yes, frames should be fast.
Often around .02 seconds
Waiting one frame would not be noticable by human eyes, but would affect logic
i thought the first one is your time and second new record
i dont see why you need to save the current time?
can you give me a simple example where waiting for one frame affects the logic?
new record time it saves the time you survived
and when you have "your time" it dosen't save that one but it shows best time (the record you survived)
All right I'm probably not understanding something. I will do some research. Thanks a lot for your time!
I feel you're still not understanding what a frame is
If you are polling a value and expect it to happen one frame, but it happens the next, so things are out of order
i dont really understand the point of your code
all you should be doing is checking if there is a best time, then comparing the time you got to the best time
yeah something like that should work, does it?
il check
when i use unity remote why does it lag so much on my phone?
depends on several things, what phone is it? does the game take lots of performance? or is it just a simple game which shouldnt be lagging at all
its a simple game for testing stuff, i have a good phone
ok it shows new record but how can i do the "your time" your menu part
you can use https://docs.unity3d.com/Manual/Profiler.html i think, should be able to see whats wrong
hello, im looking for a way to display my player's health on screen using a bar, how would I go about doing that, I've defined a health bar in the main player script just confused how to display that on the screen itself
first i would take minutes and seconds outside the if statement so you arent repeating yourself 16 times.
then you would just change BestTime to the best time, and current time to minutes and seconds
you would do this in the else statement which is when you dont get a best time
so i think i need to add "else" right?
or another "if"?
no? you already have that
you either get a new record or you dont
new record > display new best
you dont beat record > display current time and display best time
i think like this right? (your time)
i forgot to say
i got new record but when i play with lower record it dosen't appear new record or your time when i save the code like that
float minutes
float seconds
if(besttime...)
{
newRecord = true;
StartCoroutine
besTime.text = ...
setFloatBestTime...
}
else
{
newRecord = false;
currentTime.text = minutes and seconds
}
Im doing a game in a 3D engine but with 2D sprites. I did a camera with cinemachine which is fixed around my player character, and all the deco objects are always looking to the camera. but now i want, if im standing in front of a deco object the player shall be in front but if i walk behind the object, the object shall be in front. I watched some videos to do so, even in 3D with 2D sprites just like mine but i dont get it working and i dont know what im doing wrong. Can someone help me with that ?
you need to show what you tried and what is the problem
!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.
there is no script i can show you. everyone in these videos did it with the layers and layer order but it just dont work in my project. dont know how to show you that
then its not a code problem? #💻┃unity-talk
So in this case the yield return null tells the logic to wait for next frame other than doing the whole thing in a single frame.
Yes
That is the point of coroutines generally. To spread logic over multiple frames or even seconds
Or until some event has occured
Frame in this context just means the game loop right? Like renders the image gets the input and moves the player etc?
well dont know if i can do it with a script but then i need it from you
All of that.
I sent that link for the order of execution earlier. It shows exactly what happens in a frame
All right I will keep looking at that one. Thanks a lot for the answers again! Appreciate it.
i did everything and also added scrpti but this door is not opening
is the script on an object in the scene? also place debug.logs to make sure stuff runs
might be better playing an animation also instead
i tried with animation it just makes it worse idk how to implement it since i just begun like 2 days in unity
oh wait i got it
no worries
thanks a lot

Strange bug, the custom physics calculations that I prepared seem to break down on lower fps
Collisions are not working as they shouls
Hello, Im trying to implement pausing in my game since I have coroutines running basically all the time I tried setting Time.timeScale to 0 the problem is with my Unpause coroutine
IEnumerator UnpauseCoroutine()
{
countdownImage.gameObject.SetActive(true);
countdownImage.sprite = countdownSprites[0];
yield return new WaitForSeconds(1f);
countdownImage.sprite = countdownSprites[1];
yield return new WaitForSeconds(1f);
countdownImage.sprite = countdownSprites[2];
yield return new WaitForSeconds(1f);
countdownImage.gameObject.SetActive(false);
state = GameState.Playing;
Time.timeScale = 1f;
}
Since im using WaitForSeconds with timeScale set to 0 the second never passes. Is using Time.timeScale good practice in the first place and if so how would I fix my coroutine
I love having geniuses that just answer my questions cause they're nice people, I assume that means that using Time.timeScale is also an ok approach?
It is a fine approach, yes.
Using realtime will make sure that coroutine actually gets through the waits instead of hanging.
Well thats turned what I thought would be quite a complicated process into something very simple, thanks very much for your help
private void Start()
{
pi = GetComponent<PlayerInput>();
PlayerInputController[] piclist = FindObjectsOfType<PlayerInputController>();
ID = piclist.Length;
markerStart?.Invoke(ID, this);
DontDestroyOnLoad(gameObject);
}
Right now i have it so when this object is created it self sets the ID to the player count. this system breaks down when player 1 leaves while player 2 is still there for example. when they join back, they take overp layer 2 and break the game logic. how can i fix this
I've had an issue with some code basically it is meant to find the nearest object with the food tag and store it as a Vector3 but it doesn't run at all prob bcs im iterating through every object here is the code:
Not related to jam but I've had an issue with some code(unity) basically it is meant to find the nearest object with the food tag and store it as a Vector3 but it doesn't run at all prob bcs im iterating through every object here is the code:
ok almost works but
im trying to add best time record but i can't make it work i don't know how to add the timer from new record
Please don't crosspost.
The issue is not because you are iterating the objects.
- add a debug log showing how many colliders the overlap returned
- show where you call See()
- use CompareTag("food") instead of .tag ==
I think you need to store you Time.TimerCount in a variable and then use that to compare yourTime to bestTime and then do the string.Format operation to display it.
You'll have to use PlayerPrefs.GetFloat method.
bestTimeText.SetText(PlayerPrefs.GetFloat("GetTime"));
If there's a case, when the GetTime key doesn't exist in PlayerPrefs, consider using the method's 2nd parameter, float defaultValue.
bestTimeText.SetText(PlayerPrefs.GetFloat("GetTime", newBestTime)); // or simply 0f
can arrays have a null value
And I hope this is what you were referring to 
Yes, of course
Say, you have an array of GameObjects, and suddently, the GameObject with the index 2 is destroyed. The array[2] is null.
It works with any enumerables of any reference-types
An array is a reference type so an array variable can indeed be null.
Please note the difference between the variable referencing the array itself, and the values in the array
Oh, I thought they were referring to the array's items 🤔
The array reference itself can be null. And if it's an array of reference types, then each element can individually be null
any time you have a reference-type variable, it can be null.
So, "can arrays be null" / "can arrays have a null value". Pretty confusing to me
Yes those are two separate questions, and it's unclear which @stuck palm was asking.
Note of course that objects themselves are never "null". Null is a particular value a reference -typed variable can have.
it just means the variable isn't pointing to any actual object
"can arrays be null" / "can arrays have a null value"
Yes.
Hey everyone, does anyone know why I'm unable to pass a GameObject through my scripts? I've set up all the info on a scriptable object and then I'm passing that through to a manager class.
When I try and pass that on and instantiate the GameObject, I'm getting the error:
ArgumentException: Object of type 'UnityEngine.Object' cannot be converted to type 'UnityEngine.GameObject'.
It's specifically calling out the 'InitialiseMonster' method as the problem. Here is my code:
public class MonsterBase : ScriptableObject
{
public string monsterName;
public string monsterDescription;
public MonsterStage monsterStage;
public int health;
public int maxHealth;
public int mana;
public int maxMana;
public int startingWeight;
public GameObject monsterModel;
public ScriptableObject nextEvolution;
}
////////////////////// New class ///////////////////
private void SetMonsterStats(MonsterBase monsterBase)
{
monsterName = monsterBase.monsterName;
monsterDescription = monsterBase.monsterDescription;
monsterStage = monsterBase.monsterStage;
monsterHealth = monsterBase.health;
monsterMaxHealth = monsterBase.maxHealth;
monsterMana = monsterBase.maxHealth;
monsterMaxMana = monsterBase.maxMana;
monsterStartingWeight = monsterBase.startingWeight;
monsterModel = monsterBase.monsterModel;
InitialiseMonster(monsterModel);
}
Looks like your function is expecting a UnityEngine.GameObject and you're passing it a UnityEngine.Object
you'd have to look at the filename/line number of the error to know where
The code you shared doesn't have enough context (nor did you share the error details) to know exactly what the problem is beyond that.
Notably: A Scriptable Object is not a GameObject
All GameObjects are Objects, but not all Objects are GameObjects
I think I've fixed it the s ript was listening for an event which sent an object and that was inteferring with the variable and then the method
Thanks for your help
Sorry I was asking if array values could be null
That depends
if it's an array of reference types, then yes
If the array is of a nullable type, yes
if it's an array of value types, then no
There's nothign special about the values being in an array
So I can't have null values for an integer array then?
no
Okay
Correct.
If it's a type that's normally nullable, then it's also nullable in an array, and vice versa
the array changes nothing about that
This wasn't a question. I was referring to shebb asking a confusing question, so that I wasn't sure whether they meant the array's values or array itself being able to be null
I know, I was just making a joke that the answer to that "X or Y" question is "yes"
/r/inclusiveor
Got it now. This is a funny one
Strange question, but can you create your own value type? Making your own class is a reference type if my knowledge serves me right, but can you make your own kind of int or something like that?
of course
Sure
it's called a struct
Or like a bool or a string or something
strings are reference types
I should read on those cus I haven't used them
Oh really?
Yes you should
These are keywords, which have their own structs, e.g. Bool, Int32. I don't think you can make those.
They're purple on my IDE so I thought it was a value type LOL
whats the best function to use when I want smth to happen when I instantiate the gameobject that the script is on?
Awake
cool, thought so but I saw "OnDestroy" and thought theres an "OnInstantiate" or smth, thanks!
or "OnLoad"
There's an onenable
Look under the "messages" section here to see what's available: https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
i didnt know if it got called when the object got instantiated
Awake is most like "OnInstantiate"
OnEnable gets called too, but it will also get called again if you disable and re-enable it
I think it does but awake is quicker I'm pretty sure
cuz technically the object doesnt get enabled cuz the prefab im copying is enabled by default
It will still get OnEnable
oh cool
Awake is called instantly after the object is instantiated. Then Start.
Start happens like a whole frame later
Awake will have run by the time Instantiate returns
(as will OnEnable)
It is enabled when instantiated, enabled after being disabled or on the scene reload, assuming the script runs in editor (which is basically instantiated too)
also how can I move smth using rigidbody without causing issues
I mainly use charactercontrollers so i kinda forgot
i dont want to just edit the velocity
Not sure how to solve this issue here. I tried keeping a list of IDs but the IDs can only ever be 1-4 so idk if that's required
Move it correctly and it won't cause you issues
thats what im asking lmao, how to move it correctly
maybe moveposition?
Also this question is a bit confusing. How exactly do you want to move it?
I want it to move forward by a set speed
You usually use Rigidbody.AddForce / Rigidbody2D.AddForce with the suitable ForceMode, ForceMode.Force if you want it to be moved as if you set the velocity
If you're using the Rigidbody component it's implying that you're wanting to simulate Rigidbody physics or Kinematic Rigidbody physics.
like that?
Maybe tell us the error.
then set the velocity
Maybe tell us the error.
MovePosition is usually not too realistic and will definitely move the Rigidbody to the desired position. If you want the character to e.g. not go through the wall, use velocity or AddForce
Well, yeah, that's the code I sent 🤔
Oh, I haven't mentioned the error
I forgot to convert float to string.
Add the .ToString method after the GetFloat
Why is it a set float now
This is the method.
lol
if i add get float it will error a lot
It will also error with set float
I have already told you what to do
ToString is a function
Looks like the ide is already configured. There's a lack of the very basics.
the textbox is disappearing but it doesnot detect e click
im trying to make a dialogue box when i click the robot
It wouldn't detect a click. It's not even UI.
Were there any console logs?
!ide
your vscode tells you to install the extension
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
also update wont be executed on disabled object
e click
They mean pressing the e button
Oh, yeah, just mentioned it.
I thought they were trying to click on the text.
And I thought by "e" was meant "the"
nope doesnt show a thing
it does that sometimes
Figured it out in the other server. That script is on tbe same object they are disabling
you need to have a configured ide to ask for help
parentheses?
Hello
How to make the Frame per second will smooth fast and goes slow
Target frame rate
Yes, parentheses.
.ToString();
by the way kinda worked
is fixed
No, it didn't.
Ok edit the Target Frame rate
Well, yeah, of course. Have you had a look on the link I've sent?
don't worry is fixed now
Just a quick question, how would I go about creating a score counter that goes up every single time an enemy dies,
Generally use a singleton.
have the enemy class call a function on the singleton when it dies
Of course, it is. Also you didn't have to switch from the Set method for it to work.
thats what i tried to do but then it had issues with actually processing death
now i got this wtf
What kind of "issues"?
this is currently the enemy death script and i tried to use a void Score function that would incriment the score by 50
I don't see anything in this code that is calling out to a singleton score manager object.
the enemy would show it visually getting hit but not die at all
and the score going out
i removed it from the code
that doesn't sound related to the score stuff at all
that's just your damage and death logic
Where is the part of the code, which is supposed to kill the enemy?
ToString can take a formatting string as a parameter. For example "F2" would show 637.34 (two decimals)
What do you want it to show?
this was what the code befoer i removed the score function
under the void Die function
So, what's the problem?
Yes, so is it supposed to be killed by enabled = false?
If you want to actually kill the enemy, you'd usually use the Destroy method
Destroy(gameObject); // assuming the script is on the enemy
pretty much yes, when its health is 0 it plays the death animation then disables the script
what is scoreValue? This doesn't look like you're using a singleton
what is a singleton ?
it is yes
let me change that now
A script in the scene that there exists exactly one copy of. That you can reference easily from code without an inspector reference
You'll have to wait for the animation to be played, then disable the script
the issue is that the death wouldnt process when i added the Score() into the if statement under void TakeDamage
Is it because you were encountering an error?
Are you playing with the console window open?
You should not ignore errors
no there was no error in the console window
apologies there is an error
Exactly
it only appears after the enemy is hit
exactly
use a singleton
this will solve your problem
Turn the script that tracks the score into a singleton
google "Unity Singleton pattern"
the script that trakcs the score is part of the main player script though
should i just make it its own script ?
Doesn't make a difference
But yes
you should definitely make it its own script
Each script should only have a single responsibility
okay let me do that then
otherwise your code will be spaghetti
I would recommend this one
once i implement the simpleton how would I go about actually visually displaying it in the UI?
Visually displaying e.g. the text in the UI?
You would access the Singleton, which e.g. updates the score.
// ScoreManager : Singleton<ScoreManager>
public void AddScore(int value)
{
if (value != 0)
{
_score += value;
scoreText.SetText(_score);
}
}
//
ScoreManager.Instance.AddScore(1);
It can read the data from the singleton
ideally, using events, but that's a little more advanced, so you could just have the singleton reference the UI and update it, or use Update from the UI script
YES
apologies caps lock
im a bit confused about actually implementing the singleton
i created a seperate score script
but am i supposed to remove the reference from teh enemy script
because currently I use this line in the enemy script to reference the score value
so that I can update the counter from the enemy script when it dies
There's nothing to be confused about. Create a separate script and copypaste e.g. the full generic singleton from the tutorial I've sent.
public class GenericSingleton<T> : MonoBehaviour where T : Component // ...
yes remove this and use the singleton insteadl
use the singleton in the enemy script ?
No.
Depends what you mean by "use"
or is the singleton its own script ?
the score script should be a singleton
the enemy script should interact with the score script singleton
oh yeah it should be score not singleton
okay i added the float for the score counter
Now from any other script you can do Score.instance.ScoreCounter to access that ScoreCounter float
Alright, I would say so:
Enemyshould be a script assigned to every enemy in your gameSigletonis a generic class, created in a separate scriptScoreManageris a class, derived from theSingleton
public class ScoreManager : Singleton<ScoreManager>
- Every time something happens with the
Enemy, e.g. it collides with something, the score should be updated using the method in theScoreManager.
ScoreManager.Instance.AddScore(1);
ScoreManagershould manage all the variables likescoreandscoreText, which should be updated in theAddScoremethod
okay i got it
so in the enemy die section i can now just add the Score.ScoreCounter line
sure
sashok is recommending a bit of a "cleaner" more robust approach
It's probably better practice, but will be a bit more complex for you to start with
yeah it does sound a bit more complex
Score.instance.ScoreCounter
Yes that my bad^
no
I'm sure a "cleaner" approach will be easier for them to read, right? Also I feel like it's not too hard to start with 
So you want to set the score counter to 50 when this object dies?
Score.instance.ScoreCounter += 50f;
what you're doing right now is just setting it to 50
oh okay
= +50f means "set it to positive 50"
+= 50F means "set it to whatever it is right now plus 50"
that was a mistype
i didnt even realise that
thank you
okay now thats set up am i able to ust display the score as part of the UI ?
Yes, you'll have to set the text
ah wait when testing, i am recieving the same error as before
Make sure you have the TMP_Text serialized in your manager class
Please, show the 44th line
Did you actually put an instance of Score in the scene somewhere
ah wait that might be the issue
its because its not being referenced anymore
score is just a script its not tied to anything at the moment
i have this object that is the TMP for score
Yes, that's the issue. You'll have to have a GameObject with the Score script assigned to it.
should i put the script under that
Nope
You really shouldn't
Consider creating an empty GameObject like, what I usually call it, #ScriptsHolder
You may call it like ScoreManager etc.
and then i added score to that
That's right
You have to serialize the TMP_Text to store the text in your Score script
Which you then assign to your score text
so in the score script itself is where i have to reference the TMP SCORE and then update it
Yes.
What is it supposed to mean?
You simply serialize it using the SerializeField attribute
in the code is there like a command that i can reference the tmp object
No, serialize and drag it manually
And I would highly recommend to create a method in the Score script, which manages both setting the score and updating the text when parameter passed isn't 0
I'm not blaming you
ðŸ˜
how would i go about that
First serialize the text. Have you done that already?
no im a bit confused what to write after SerializeField
i wrote score
not sure if thats right
It's not
The SerializeField is the attribute, which should be written in []
The score's type is TMP_Text
so that ?
So,
[Attribute] accessModifier type name;
No
Now that's the puzzle for you to solve
Yes, that's already right. But you should usually put the access modifier to readability
I would recommend putting private before TMP_Text
(Even though it's already private by default)
Drag it to the scoreText
Additionally, we use thisCaseToSeparateTheWordsForThisKindOfNames
oh yeah woopsite
That's right
after that then how do i actually update the text itself with the value ?
do i have to convert the float to string
I would first consider creating a method in the Score class.
Consider naming it like AddScore
And it should have a parameter, guess, float is what you use.
Consider adding an access modifier before the method's return type (which is void and returns nothing)
(Although an access modifier isn't important)
so like public or private ?
You want to access the method from another classes.
Yes, that's the right conclusion
Now reread this.
I have said before the method's return type
i am a bit confused
It would probably be wise to also rename #ScriptHolder GameObject to something more meaningful, such as ScoreHandler, to avoid any confusion later on
Reread the message, previously sent by me
Between the accessor (public) and script name (AddScore) you need a return type
you should consider going through some basic c# courses so you understand the syntax of the language and how to correctly structure and write your code
yeah kinda an unfortunate situation, its meant for a school project, so I havent got as much time to properly learn unity
i am typically used to using GMS langauge not C#
Yes, I have already mentioned it here #💻┃code-beginner message, but I like to call it #ScriptsHolder if it has multiple scripts on it, which it, yeah, currently doesn't
ohh public float addscore
right
why are you returning a float though
Not the float, you wouldn't need to return it
that doesn't answer the question
You likely want the float as a parameter
For how much score to add
Unless it is always a set amount I guess
It doesn't matter.
AddScore simply adds the score. You just call it without needing to get anything from it.
Score.Instance.AddScore(1); // that's all.
Well, "scripts holder" is still pretty vague, it can be anything, and you'd typically want to more or less know what a gameobject holds by reading it's name
Like, "UI Handlers" or anything
if i do that it flags it as wrong
That is not how you declare it, it's how you call it
yeah at this point you are just wasting your time by trying to code by approximation rather than actually understanding what you are doing. #💻┃code-beginner message
I have a script holder, which holds GameManager, TargetManager, LevelManager, BehaviorManager etc. on it. I find it pretty hard to find an another suitable name, but pretty easy to have a whole look on all of my singletons.
What's the error?
It is clearly completely incorrect. It doesn't matter too much what the error is.
Likely about being a top-level statement though
as previously mentioned would love to actually understand but im kinda just learning as i go here since its the only choice i have
Why is there a curly brace after this line
it's not a condition
Because it's in the wrong place. Outside of the method.
It is not the only choice
It seems like that AddScore is just being called to me, why is it completely wrong lol
Because it is not in a method
why didn't you pay attention in class? surely if this is a school project your instructors would have covered how to write the code
Read my previous message.
They replaced the method declaration with that
Oh yeah didn't catch that
You are spending longer trying to resolve this by random guesswork than you would learning how to call a function
was taught python in class, is an end of semester project
https://www.w3schools.com/cs/index.php
Just take the hour or so and do this
Relative to indentation and the curly brace, they probably had try to define it like a method where instead they're wanting to make a statement call.
decided to use C# because using python for games or any game related thing was way too slow and inefficent
Well, everyone has their own preferences, I'd just group them under "Managers" and let each of them have a separate GO
Have you tried a unity tutorial?
watched multiple to build what im currently working on
Yeah, because it's not designed for doing games
surely not nearly as slow an inefficient as what you are doing by brute forcing your way through making a game using a language and engine you don't understand
i mean for the most part it was going pretty fine, im just self teaching at the moment, i have a game working fine i just wanted to learn how to do a score counter
Don't use youtube. Your issue is with c# more than unity. Do this:
https://www.w3schools.com/cs/index.php
you need to start by learning how to write c#. just like how you learned to run by first starting to crawl
is not supposed to be like that
It is 3D, right? 👀
is supposed to be like this
Best time is the record you made (new record)
i intend to learn but like also previously mentioned ive got about 4 huors to finish this up so i dont really have the time to just teach myself everything
then you certainly don't have enough time to finish it considering you don't even know how to write a method
This is a common occurrence in the server.
So less than one hour to do this course would leave you three hours to breeze through the rest
https://www.w3schools.com/cs/index.php
i definitely do have enough time to finish it considering ive got the actual gameplay part of my game finished, i understand how to write a method im just being told stuff in ways i do not understand or unclear wording
i will do this then
I see, well, the text on the image you've previously sent isn't parsed correctly and is shifted to the bottom because of the rect's small size.
Consider using a parsed, which you, I guess, have already used before, and making the rect wider.
copying someone else's code doesn't really count as writing your own gameplay. anyone can go along and copy a tutorial line by line
i watched a couple videos on the basics, none of my code is copied
i watched videos on basics like movement and handling stuff i intended to put in my game and the rest was just done by trial and error
Oh, so am I that bad at explaining..?
nono it is not your fault i am just bad at understanding
I think your explaining was pretty clear
Well, anyway, I would suggest you, as you were already suggested, to take at least a few hours to simply go through C# basics, which can be achieved using a variety of tutorials. This way you'll get way better at understanding and thus implementing stuff in Unity.
Well, there certainly can be improvements.
Access to the entire source code would be nice.
A sample setting using the code would help as well.
Don't forget a video demonstration!
Joking - off-topic
yes i will do this
i am just strying to implement what you were saying before
then i shall look through C# tutorials
Is it ok to rather give an access to the entire unity scene, rather than the unordered code snippets?
"i just want to do this one thing. then i super pinky promise that i'll go learn the basics. i promise"
Alright, no, let's make it vice versa, right?
dude what is your deal😠i just wanna get this project done before its due in 4 hours and then i intend to actually look over unity basics so i can code in this language
my bad for being on a time crunch i guess
How long time have you even had for the whole project?
Maybe you should show more of the code and the actual error.
roughly a week or so
this is the entire script
Oh, and you have 4 hours left to finish?
yes
it is due at midnight for me
I would have had 30 minutes, had it been me
I'm assuming with the inferred lack of basics and squiggly line, this implied you had called the statement in an inappropriate scope.
because i've heard this tired bit dozens, if not a hundred times at this point. can you guess how many times that person who just "wanted one thing" actually went and bothered to learn what they were doing instead of coming back the next day asking for help with "just one thing and i'm on a time crunch so i don't have time for tutorials right now"
A good question to ask yourself is if you understand this
i mean yes because i am actively teaching myself GMS and intend to learn unity and C# because thats exactly what im going to university for
how can I move an object forward using AddForce?
it benefits me more long term to actually understand unity and c# as thats whats used at the university i am attending in september
Yes, haven't I mentioned it in our previous conversation?
yes
my main problem is that it doesnt move forwards relative to it's rotation, it just moves towards a specific point
all its doing currently is setting up the scorecounter variable that can be accessed by other scripts and updated, using a singleton it creates an instance of the script that can also be changed from any other script and accessed
Alright, let's just finish it.
Create a public method in the Score class with the float paramater.
public void AddScore(float value)
The method should
-
- Update the score
_score += value;
-
- Update the text
scoreText.SetText(_score.ToString());
Don't forget to first check whether the value is 0 to increase the performance.
The method should be called whenever you want in the Enemy class.
Is this all? Yes.
Use the add force function and your target's forward direction scaled by some value to move forward.
Nice 🙂
nvm im stupid, rb.AddForce(transform.forward, ForceMode.Impulse); was it all along
....i used Vector3.forward........
If you're just looking for code, there are examples in the docs
i am very aware of what i am coding and understand it after i implement it, its just that when it comes to implementing things i am not sure the specifics of how to do so always
No problem
when using the value; is that an interchangable thing or does it specifically need to be labelled value
or will it be something like 1 or 0
i created the public method
What do you mean? Are you referring to the parameter's name?
im just confused as to where the value is being taken i wouldve assumed it wouldve just been as simple as having like a variable defined at the top and then just adding to that via a method in another script
The value variable would be the alias for the float you're passing to the method - how you'd refer to the float.
The parameter in the function
I'm sorry, I don't seem to understand it.
oaky so im using ScoreCounter then in the paramater
since thats the value i want to display
on the text
right
//Somewhere in Start()
AddScore(5f);//Usecase```
i thought you said you learned python? python has function arguments. this is the same thing
What is ScoreCounter?
the variable i set up that acts at the place where the score is updated when an enemy is defeated
the parameter is value, public void AddScore(float value) the parameter is a float and it's called value
right that makes more sense
Well, I have no idea. How many points should be added when an Enemy dies?
adding 50 each time
Seems wrong, AddScore should add score, not set it to the passed value, similarly in point 2, it should use _score and not value
So use 50.
but i assumed that'd be handled as a part an enemy script not here
You're right. It was a typo, I'm sorry.
Corrected.
Point 2 is still wrong
Well, assuming you had a "OnDeath" function on the enemy then you would simply call "ScoreManager.Instance.AddScore(50)"
This is good now
[SerializeField] private float _score;
public float Score
{
get => _score;
set
{
_score += value
scoreText.SetText(_score.ToString());
}
}```
yeah my enemy script has an on death
Yeah, you got it
that was already set up
That's wrong. You have to update it to use the actual method, as cat kat has mentioned before
ScoreManager.Instance.AddScore(50f);
Yes, that's all.
Yes now it's right
Also you may consider creating a variable from this 50
And make ScoreCounter private for good measure
gotcha
since it neither needs to be public nor serialized
You usually create a _score variable and Score property
private float _score;
public float Score
{
get => _score;
set => AddValue(value - _score);
}
itll be 50 each time so i dont think i need a variable for it
Then you definitely need a variable for it
okay nevermind i was wrong then
Well, by AddValue was meant AddScore..
you don't need that property at all 🤔
or you could switch to it
but you're in a weird hybrid mode right now
but the function alone was fine for now
Well, you have several possibilities to set the value. I wouldn't consider it being wrong.
Also the name of the variable is the same as the class, which could bring up some issues
Property
I tend to use properties only to return a private field value, and methods when more things are involved, such as updating the UI
stuff
idk this property is just complicating things
wait i forgot to change Score
and isn't really needed right now
It isn't.
It's not complicated for someone who knows what they're doing but that does not include @quaint anchor
appreciate it
luna does exactly know what they're doin!
i added the property and changed the float name to ScoreAlt to avoid confusion
I don't see why it would confuse it
Having a variable and a property for the same class with different names is what indeed gives you the confusion
so it was flagging it as an error since the name was the same as the class it was enclosed in
ide didn't like it
Well, yeah, that's not because of the variable.
well
The property is supposed to be called Score. The class should be called like.. ScoreManager..?
yeah its just an error w how i named the script
is scoreText assigned?
yeah in the editor
It is
The scoreText isn't assigned
Because you renamed it from scoretext to scoreText.
The field stores its value by the name, that's why changing its name makes it lose the value.
odd..
my score finally incriments
Yey!
i am very happy that worked
thank you very much for your help
i will now go and do some unity lessons
What is that, that is odd?
so i can finish the rest of this code
C# *
no, nothing now. i typed that b4 realizing he had renamed it
Strongly agree
Hello,
I am trying to replicate this animation on unity using gizmos and lerp. I figured out on how to do the center sphere animation, the problem lies with the others and their movement any recommendations?
Thanks!
I am struggling to understand the logic of the code for anything other than the center.
Mostly just looks like a bunch of sine functions and such
or just moving in a circle of increasing/decreasing radius
You'd have to analyze how each thing is moving ¯_(ツ)_/¯. If you can play it in slow motion that may help
https://gdl.space/utebizopoq.cs <-- script
script stop reseting the first dash cooldown for some reason
it worked but the thing to fix is the timer
counter
Show the code
is there any reason why this piece of code wouldn't work?
ik that the code actually runs from the debug.log but it doesn't actually work when I check it out in the inspector
If the log runs, then whatever component instance is gets enabled.
Whether or not it stays enabled is another matter, but if the log happens then it's definitely enabling it
ooh okay that makes a lot of sense
just to make sure if a script has a DontDestroyOnLoad then even though it enters a new scene it will redo the start and awake methods right?
no
the only thing that I have that disables the script is disabling it in the start method, but it won't run again when changing to a new scene?
Start runs before the first Update call this object exists for
The delays before your messages are insane.
As I have mentioned in my previous response, parse the string as you've done it before.
mb i shouldve made it clearer. The code i showed is an event that runs the moment a scene is changed. So i think its running before the start method, and the start method ends up disabling it again.
If this function runs on the first scene this object exists for, then it would run before Start. The scene load happens before the first update
gotcha thanks for the help!
thanks!
no, does it not occur to you to go and read the documentation?
i couldnt find the docs
sorry man
i was trying to find a way to add the text fixed to make the timer like 00:00 and not (number).(number)
You want to get the float from the PlayerPrefs and, if it's in seconds, multiply it by 60 to get the minutes.
Literally use the same method you've used before
private void RegisterPlayer(PlayerInputController player)
{
print("adding " + player);
players.Add(player);
player.ID = players.Count;
markerStart?.Invoke(player.ID, player);
}
i'm getting the stuff in the console, but in play mode the list doesnt update. players is a list of type PlayerInputControllre
but in play mode the list doesnt update
What list? How do you know it's not updating?
i was trying that but i got the same
the list in the right where it says players has nothing in it
Maybe that's not the list your code has a reference to
Then either you're looking at the wrong list or something's removing it later
How and where are you calling RegisterPlayer?
when a player input controller is created, it sends out an event that the characterselectmanager receives and calls register player
which CharacterSelectManager receives it?
How is that set up?
Maybe you're not referencing the one in the scene
maybe you're referencing a prefab or something
https://gdl.space/utebizopoq.cs <-- script
script stop reseting the first dash cooldown for some reason
When I'm asking "how and where" I'm kind of looking for code
private void OnEnable()
{
_inputs.Play.Enable();
CharSelectMarker.ReadyConfirm += AddReady;
PlayerInputController.sendRegister += RegisterPlayer;
PlayerInputController.sendRegister += UnregisterPlayer;
_inputs.Play.B.performed += ctx => CheckBack();
CharSelectMarker.ReadyRemove += RemoveReady;
}
PlayerInputController emits sendRegister on awake
Looks like you're subscribing both Register and Unregister to the same event
so it's likely adding it and immediately removing it
Adding a log to Unregister would have been my next suggestion
(if I knew it existed)
mb i should have provided more context
Is there an easier way to write this offset position out?
Vector3 offset;
Vector3 positionWithOffset = transform.position + (transform.right * offset.x) +(transform.up * offset.y) + (transform.forward * _offset.z);
Vector3 positionWithOffset = transform.TransformPoint(offset)
or:
Vector3 positionWithOffset = transform.position + transform.rotation * offset;```
The former takes your object's scale into account.
The latter does not.
awesome thank you!
Anyone know why my text is not showing up ingame?
it shows up in saying it should show in my debug log but in game it doesnt show
public class HudController : MonoBehaviour
{
public static HudController instance;
public void Awake()
{
instance = this;
}
[SerializeField] TMP_Text interactionText;
public void EnableInteractionText(String text)
{
interactionText.text = text + ("F");
interactionText.gameObject.SetActive(true);
}
public void DisableInteractionText()
{
interactionText.gameObject.SetActive(false);
}
}
What calls EnableInteractionText
void SetNewCurrentInteractable(Interactable newInteractable)
{
currentInteractable = newInteractable;
currentInteractable.EnableOutline();
HudController.instance.EnableInteractionText(currentInteractable.message);
}
void DisableCurrentInteractable()
{
HudController.instance.DisableInteractionText();
if (currentInteractable)
{
currentInteractable.DisableOutline();
currentInteractable = null;
}
}
}
Question continues, what calls SetNewCurrentInteractable
yeah i used a debug log and it runs it but it just doesnt show up
Where did you log
under
interactionText.gameObject.SetActive(true);
and
interactionText.gameObject.SetActive(false);
also under
HudController.instance.DisableInteractionText();
Different things, I presume? Did you disable Collapse in your console so you can make sure what order they come in?
Make sure that it's not deactivating it after the activate
I believe it is, the debug log only pops up once when its set to active but the DisableInteractionText debug log is always going
lemme run it again with Collapse and see
without collapse
If you are getting the "activate" text once, and the "disable" text over and over, that would mean that it's deactivated
void SetNewCurrentInteractable(Interactable newInteractable)
{
currentInteractable = newInteractable;
currentInteractable.EnableOutline();
HudController.instance.EnableInteractionText(currentInteractable.message);
Debug.Log("Text ON");
}
void DisableCurrentInteractable()
{
HudController.instance.DisableInteractionText();
Debug.Log("Text Off");
if (currentInteractable)
{
currentInteractable.DisableOutline();
currentInteractable = null;
}
}
}
So im getting the "Text Off" constantly even without looking at the object
but im getting the "Text On" Once while looking at object
public void EnableInteractionText(String text)
{
interactionText.text = text + ("F");
interactionText.gameObject.SetActive(true);
Debug.Log("Enabling Text");
}
public void DisableInteractionText()
{
interactionText.gameObject.SetActive(false);
Debug.Log("Deleting Text");
}
}
Same with this one
So that would explain why it's not visible.
Because it's getting deactivated every frame
so ill need to only delete when i look away
Yes
How would i do that?
Using a if statement?
or would i just need to move the disabler to another spot
You never actually told me what calls these functions so I can't answer that
EnableInteractionText
public class HudController : MonoBehaviour
{
public static HudController instance;
public void Awake()
{
instance = this;
}
[SerializeField] TMP_Text interactionText;
Also i deleted both functions that delete the text and still the text doesnt show up
So, you have nothing disabling it, and the text doesn't appear?
yeah
Instead of logging "Enabling Text" here, log interactionText.text
Does it still log, and does it log the value you expect
Yes it logs the value i expect
So then it is definitely setting interactionText to the string you want
Either the thing you're looking at isn't interactionText or something else is setting it afterwards
hey if i wanted it so when i click a ui button such as a picture of a couch it allows me to place a peice of couch in a 2d environment top down i understand the logic of it i dont understand how i would go about coding it imt rying to make my first proper game ive made about 20 short platformers this game is basically each time you click play a new procedually generated cottage entior is made and you decorate the empty house
a button has a OnClick already in the inspector
you would attatch that to a method which would instantiate/activate a sprite or game object which would be the highlight of the couch
im mainly looking for pointers on how to place the object down only on a tilemap with "floor" layer i shouldve been more clear srry
would the object be interactable and stuff? a tilemap wouldnt be best then probably
it isnt placed in the tilemap layer but i dont want it so the couch can be placed on a wall its hard to explain let me gets some images
so i want to try make it when i click if the player has the furniture hovered over a wall or in a void it will reject the placement but if its hovered over the floor it will accept
multiple different ways to do that
first you should focus on creating the actual object that will be moving around and placable
ok ill get back to the discord when ive completed that
The thing im looking at is a Interactable but should have under my crosshair a interactionText
public class PlayerInteraction : MonoBehaviour
{
public float playerReach = 3f;
Interactable currentInteractable;
void Update()
{
CheckInteraction();
if (Input.GetKeyDown(KeyCode.F) && currentInteractable != null)
{
currentInteractable.Interact();
Debug.Log("You pressed F on it");
}
}
void CheckInteraction()
{
RaycastHit hit;
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
if (Physics.Raycast(ray, out hit, playerReach))
{
if(hit.collider.tag == "Interactable")
{
Interactable newInteractable = hit.collider.GetComponent<Interactable>();
if (currentInteractable && newInteractable != currentInteractable)
{
currentInteractable.DisableOutline();
}
if (newInteractable.enabled)
{
SetNewCurrentInteractable(newInteractable);
}
else
{
DisableCurrentInteractable();
}
}
else
{
DisableCurrentInteractable();
}
}
else
{
DisableCurrentInteractable();
}
}
void SetNewCurrentInteractable(Interactable newInteractable)
{
currentInteractable = newInteractable;
currentInteractable.EnableOutline();
HudController.instance.EnableInteractionText(currentInteractable.message);
Debug.Log("Text ON");
}
void DisableCurrentInteractable()
{
if (currentInteractable)
{
currentInteractable.DisableOutline();
currentInteractable = null;
}
// HudController.instance.DisableInteractionText();
// Debug.Log("Text Off");
}
}
Is the interaction script
If your debug log after setting interactionText.text is displaying the text you're expecting to see in interactionText, but you aren't seeing it, either the thing you're looking at isn't interactionText or something else is changing it before you see it
i dont see what could be changing it if the only thing that deletes it is commented and there is no interactable things besides the one im looking at
So if something else isn't changing it, then the thing you're looking at isn't interactionText
wym the thing im looking at?
Like the object?
The thing you're expecting to display the text
You've logged interactionText.text. If that logs what you expect it to, and there's a text thing you are looking at that doesn't, then those are not the same object
So, this object's text is not changing?
Yeah
Then this is not interactionText
Assuming everything else you've told me is true
how can it not be interactionText
What did you set interactionText to
Show that
Okay, now, click on that. What object highlights in the hierarchy?
Okay, then one of the previous things you've told me is false
Since this is interactionText, and your log shows that interactionText.text is what you expect it to be when you expect it to be that, then something else is changing it
It logs correctly in the console
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Runtime.CompilerServices;
using System;
public class HudController : MonoBehaviour
{
public static HudController instance;
public void Awake()
{
instance = this;
}
[SerializeField] TMP_Text InteractionText;
public void EnableInteractionText(String text)
{
InteractionText.text = text;
InteractionText.gameObject.SetActive(true);
Debug.Log(InteractionText.text);
}
// public void DisableInteractionText()
// {
// interactionText.gameObject.SetActive(false);
// Debug.Log("Deleting Text");
// }
}
This is the HUD script
Nothing in it changes the text
If that log is logging the text that you expect it to be, and that's not the text you're seeing in-game after this runs, then something else is changing it
You've shown evidence that it's the correct object, and that the log is printing properly, so simple deductive reasoning shows that since it is correct at this time, something else must be making it incorrect after this runs
after it runs would be a void Awake or void start/update?
update runs every frame, so it would work
start runs at the start same with awake correct?
awake runs before start
yes
So would it be my void awake
the instance: = this;
can someone help me ?, Im doing a arrow that points to a enemy position based on the player position and rotation but the code that i have dont work very well
Vector3 FirstPoint = (Player.position - transform.position).normalized; // Direção inicial do objeto
Vector3 LastPoint = (Inimigo.position - transform.position).normalized; // Direção final do objeto
float angle = Vector3.Angle(FirstPoint, LastPoint);
Quaternion PlayerRotation = Player.rotation;
float KartYrotation = Player.eulerAngles.y;
if (KartYrotation > 180f)
{
KartYrotation -= 360f;
}
Quaternion rightrotation = Quaternion.Euler(0f, 0f, angle - KartYrotation);
transform.rotation = rightrotation;
!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.
what do you mean by doesnt work very well
the arrow just flip flop randomly
i did it!
you can place furniture now
nice, now detecting collision against walls
would i do like a constant update every time it changes a square on the grid to see if its on a tilemap cell and if its not dont let the mouse move
if someone can go call with me to understand better my problem I would be very grateful if you could give me some help
depends on your game, not necessarily not let the mouse move but just dont let it place and make an error popup or something up to you
send a video of the problem, not many people if any will go in a call/dm
i might make the couch shake a bit and not place sounds better
i dont know specifically whats better for performance.
but you can check position, you can check if a Trigger collider is on the tilemap, use a raycast, and probably a couple other ways
trigger collider sounds intresting
might go with that one
but the game isnt relativley performance intensive eitherway
also how to postproccess on cinemachine?
the arrow is tike that
the same way as normal post process i assume?
does it work if you place a normal camera?
let me try delete my cinemachine
I fixed it
Very simple fix
vcam uses reg cam, u just enable it on the camera like a non-cinemachine project
for urp atleast, been a while since i used the built in rendering pipeline.. but was teh same way, even using the post processing stack, u did ur volume / layers and w/e and just applied that to the regular cam
i enabled it but it still doesnt work its 2D
Hello, i am very beginner, i know only basic of coding, but already experimented a lot of thing, just for hobby, i want to make a simple 3D RPG game. Can you give me a few advice, tips tricks for a beginner? Also i really like database systems, any way to handle weapons, items, monsters etc like a database? Since i want to make a singleplayer game a real database not needed, but i like that structure.
do 1 thing at a time instead of focusing on trying to make it all
want to go step by step, also first i want to plan everything, and yes go step by step. already tried to make little games back then, and i learned that, one thing at a time, or it will be a mess 😄
If you are not familiar with them already, I would look into programming patterns and code architecture, it may help with breaking your logic into steps and managing your code so it doesnt become super messy, albeit it does take some trial/error to get familiar with patterns and implement an architecture that works well with your workflow - I think ScriptableObjects are the easiest to use for data in Unity but if you wanted a more flexible solution, you could look into NoSQL databases, which are basically just local databases that dont exist on a cloud - though an RPG, even a simple one may be a bit of a big project, but also a nice genre to learn making generic and modular code in, be sure to look into source control once you get started, as youll likely need to revert changes (or just have a backup) at various points of development
look into NoSQL databases, which are basically just local databases that dont exist on a cloud
huh?
hello i have a question, I am currently trying to make a results screen for my game that shows a couple values, i have the results screen showcasing but was wondering if there were some issues with my code, my goal is to showcase a number next to the enemies hit field that relates to a number that is divided by 50 to get the number of enemies, but for some reason it is not showing up
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ResultsScreenScript : MonoBehaviour
{
public static ResultsScreenScript instance;
public float _score;
//place TMP for enemies hit in here
[SerializeField] private TMP_Text enemiesText;
//place TMP for grade in here
[SerializeField] private TMP_Text gradeText;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public float ScoreAlt
{
//gets score value from _score then sets it in the addscore method
get => _score;
set => AddScore(value - _score);
}
private void Awake()
{
//checks if instance is relevant and functioning
if (instance == null)
instance = this;
}
public void AddScore(float value)
{
//displays score on TMP in game
_score += value;
value = value / 50;
enemiesText.SetText(value.ToString());
}
}
does the method actually run?
did you debug.log the value and the text after changing it
okay yeah so after checking the method doesnt run
nothing shows up in the console
well thats probably why the text doesnt work
does nosql affect performance higher than the scriptable object? so should i stick with ScriptableObject, or can i use NoSQL without worries?
i am confused why it is not running though
it is meant to be a passive script that is always active in the scene
what are you doing to attempt to make it run
the code i just pasted
its attached to an empty object
with just the script inside
it is meant to log the player's score over the course of the song and the relay back the information to them
but you still need to add score for it to run
Show where you call AddScore
it wont just do it by itself
addscore is called in the enemy script when it is killed
thats a different one
oh in the
this script is called ResultsScreenScript
Is this in Score?
its in two scripts
in both score and results screen
Why?
its tracking the same thing
No it isn't
they arent connected if you think thats what they are
oh
Having two scripts is probably causing you confusion
Always
doesnt even make sense for it to be in more than 1
these comments are absolutely useless, may as well get rid of them too
just throwing it in there for grading
specifies to comment on code as much as possible
on code, not variables
alright
well now that ive done that when im taking in the score do i just output it the same as addscore ?
i have this method
so i assume id just replicate that under a diff method name
and then do what i did before
yeah
idk is it? you tell me
id like to hope so
I may be thinking of something else? Ive seen solutions that let you handle databases locally (as a file or with a local connection), it can also exist online or with a service like Firebase, but IIRC, it doesnt have to
I think all database languages can be used locally.
I use sqlite locally on my current project
it is not working for some reason and im a little confused because of it
i followed the same methods i did to showcase my score on screen during gameplay but for some reason it is not working now
well
what is _score
what does that represent
its a variable that holds the value of the players total points
and is "points" supposed to be the amount of enemies hit
or is that something different
it is but also isnt, each enemy hit is worth 50 points
which is why i divide points by 50 at the end on the results screen to get the actual number of enemies hit
ok so
private void EndGame()
{
var value = _score / 50;
enemiesText.SetText(value.ToString());
}
I have a question about colliders. I have an interaction circle that detects collisions with a tilemap collider, but I noticed that my debug does not go off when i collide with a new tile while another tile currently inside the circle. I'm guessing this has to bdo wit hthe tilemap collider and all the tiles being the same collider, so I was wondering if there were any workarounds
how come the grade text is not showing though, i assume it is not limited to the score display
idk what the grade text is or where you do that stuff
{
public static Score instance;
//keep track of the value of the score
private float _score;
[SerializeField] private TMP_Text scoreText;
[SerializeField] private TMP_Text enemiesText;
[SerializeField] private TMP_Text gradeText;
public float ScoreAlt
{
//gets score value from _score then sets it in the addscore method
get => _score;
set => AddScore(value - _score);
}
private void Awake()
{
//checks if instance is relevant and functioning
if (instance == null)
instance = this;
}
public void AddScore(float value)
{
//displays score on TMP in game
_score += value;
scoreText.SetText(_score.ToString());
}
private void EndGame()
{
var value = _score / 50;
enemiesText.SetText(value.ToString());
}
public void FinalGrade(float value)
{
//displays grade at end of the round
if (_score >= 8000)
enemiesText.SetText("A");
if (_score >= 6000)
enemiesText.SetText("B");
if (_score >= 4000)
enemiesText.SetText("C");
}
}
but the main thing i assume is your just nto calling any of these methods
they are just sitting there
like where do you call EndGame or FinalGrade?
Ah, ive started recently looking more into database solutions to help replace some ScriptableObjects in my projects, though im still researching some of the various solutions for it
i mean you wouldnt be doing it the same way
because this isnt the same thing
Ohhh was about say lol nosql can be cloud or local. It just means non relationional database basically , usually saved as blob data or like json variant
where you have logic where the game ends
Score.instance.EndGame();
same with FinalGrade
this wouldnt be included in the score script though no ?
bump
each of those if statements will run. if the score is over 8000, it will be replaced with both of the following checks and end up with "C" as the final text . . .
idk, it would be where you have logic for ending the game
my logic for ending the game is under a different object
ok so thats where you would put it probably
okay that makes sense
Use a raycast/circlecast
alright thanks
would i need to reference the original script though
just tell me what Score.instance.EndGame(); does please
when i place it in the other script it says it does not exist in the current context
where is this
refrences the script
in the middle of the script in some random place
in the same script that handles ending the game
where exactly
show the surrounding lines
you do realise this needs to be inside a method right?
you arent declaring a variable
you are running code
Im not sure on the performance difference, though one benefit is with a database, you can access and change your games data outside of Unity, with ScriptableObjects, you can directly pass them as a reference to objects to share or clone data (such as spawning weapons with the same base stats, or playable characters), you can use either or both if your project is intended for learning, though with an RPG that usually has tons of data-driven content, a database may be easier to manage in the long run, albeit it might take more time to setup/learn
okay so id just put it in the oncollison method then
since thats whats dealign w ending the game
like i said multiple times, put it where the logic is for ending the game
so if thats where it is
If you want to end the game the same frame you touch anything, sure
Might be nice to validate the collision though
then thats where it should go i suppose
its for one specific object designed to end the game and comes last
yes but getting error due to protection level
what error
whats the code
because EndGame is private
you are accessing it outside its own class
so it should be public
you made it private. it can only be called within the class which created it . . .
when trying to do the same though i get flagged w a different error for finalgrade, do i need to remove the value float from the paramater in the original script
read the 1st line on that popup box