#💻┃code-beginner
1 messages · Page 306 of 1
that's not at all what you wanted
that's an unordered collection of just the values in the dictionary
you are in 2D, your method is for 3D OnCollisionEnter, OnCollisionEnter2D
ah thanks man i kiss your hearth
omg its workig i love you man
is there a way to set a value to a list limit?
set it to the lists length?
it has a variable for that
if I want the list to have 15 objects can I preset that?
yes
quick question is Time.time since the application started or since that scene ur in has loaded?
thats a completely different question?
That was an example
and you would do that by List<> myList = new List<>(15); if im not wrong
not with a List no
this preallocates memory for 15 elements but the list size will still be 0 when creating it
if the list is intended to be exactly a known length and not grow or shrink, you should just use an array instead
Yeah this is what I found
You don't explicitly set the size of a List; the size comes from the number of items in it. (Capacity is only for the internal size of the List and something you would rarely if ever use.) If you want a List with a particular number of items you can convert an array to a List
That will also still allow it to go over 15 elements, to be clear. You can also just create your own function which checks the length then adds if it's not at max capacity
sure or add a bunch of empty or placeholder elements to it
but yeah if you want to set a max size for your list you'll need to write a little wrapper code around it to enforce the limit
I can't add to an array at runtime can I
You can set elements in the array at runtime
or create a new larger array at runtime
which is essentially how lists work
Yo guys I want to made the UI panel to fade its alpha to clear when it is awake, how do I do this?
if you want it to not be instant, it would be best to just make an animation and just play the animation
depends how much work and how quick you want it done, you can pick the way to do it
Bet
Yo anyone know what name I need to reference the audio source in code. Wanna add the volume to a slider
AudioSource
i need help again please, my player shoots projetiles and the projetiles should be make damge on an objekt "Enemy" but nothing works how do i do it do someone know it or know about a good youtube video
show something? the code
Maybe show what you've tried
both objects
it hard to explain
then its waaaay harder for us to help
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thanks
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
now show the inspector of both the bullet and the enemy
i only made a script for the enemy i though that wenn the script says, when tag "Bullet" collide with Gameobjekt it will be destroy
yes but it has some requirements
- IsTrigger , 2. Rigidbody2D, 3. the Tag
Or CharacterController, but that is unlikely to be used for a projectile
At least hopefully hahaha
//LogicScript.cs
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public TextMeshProUGUI scoreText;
public GameObject gameOverScreen;
public BirdScript birdIsAlive;
//increase score
public void addScore(int scoreToAdd)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
//restart game
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
gameOverScreen.SetActive(true);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive == false)
{
restartGame();
}
}
}
//BirdScript.cs
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class BirdScript : MonoBehaviour
{
public Rigidbody2D myRigidBody;
public float flapStrength;
public LogicScript logic;
public bool birdIsAlive = true;
public LogicScript gameOverScreen;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive == true)
{
myRigidBody.velocity = Vector2.up * flapStrength;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOver();
birdIsAlive = false;
}
}
im trying to make the game reset if my player character is dead and if the spacebar is pressed and im having an issue where it resets every time i press the space bar. heres my code
sorry for huge block of code
then that wouldnt work im pretty sure? it needs to be a Rigidbody
!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.
Nope
CharacterController works too.
If rigidbody, it needs to be dynamic though
OnCollisionEnter does NOT work with CC though
idk about that, but its 2D anyway so character controller wont work
Ah, missed that. But yeah, it absolutely does in 3d
doesnt even mention that in the docs for OnTriggerEnter, but i dont use CharacterController so idk 100%
Yeah, it unfortunately doesn't mention it. But I do know it 100%
Ok so you confused the shit out of yourself with your variable name here:
public BirdScript birdIsAlive;```
You named your BirdScript reference birdIsAlive. So what you're actually doing with
`&& birdIsAlive == false` is just checking if you have a valid reference to the bird script. Which apparently, you do not. So that's always true. What you should do is name your variable properly:
```cs
public BirdScript bird;```
Then when you want to check if it's alive you would be doing:
```cs
if (!bird.birdIsAlive)```
ANyone knwo how I can access volume in script?
you can check the docs
or just place a . and the IDE will autofill the possible solutions
I tried the dot to no success but let me see the docs
I feel like you just said rtfm
is your IDE configured?
Dont know what that means, but I looked through the list and the values there werent working properly
IDE is your code editor, Visual Studio for example
is it configured means does it suggest things and highlight errors etc
to be fair, there are gonna be a lot of members associated with unity stuff. Just look through the docs
Yh it is
I have this Stab Goblin Character. It is an Enemy, that when it gets close to the player will attack him. The issue is that the attack Collider that hits the Player does not keep colliding with the Player even though in the Goblin Script, it keeps disabling and enabling the Collider. This is the Collision script on the Player: private void OnTriggerEnter2D(Collider2D collision) { if (collision.TryGetComponent<GoblinKnife>(out GoblinKnife goblinScript) && !goblinScript.hasHit) { print("hit"); TakeDamage(goblinScript.knifeDamage); goblinScript.hasHit = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.TryGetComponent<GoblinKnife>(out GoblinKnife goblinScript)) { print("hit Exit"); playerScript.currentHealth -= goblinScript.knifeDamage; goblinScript.hasHit= false; } } THE KNIFE OBJECT IS THE OBJECT WITH THE COLLIDER*
how do you do it?
!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
wait i send you the bullet and enemy script then tell what i am doing wrong pleay:,)
!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 told you?
i also had a question here which you didnt respond
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Why not just have the Goblin script do a direct physics query
enabling and disabling a collider and using OnTriggerEnter is kinda... wacky
https://hastebin.com/share/uhelupejow.cpp and this is the bulet script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How should I add it to the Goblin Script?
changing the way you take damage has absolutely nothing to do with the original problem
not really sure what you mean by this?
I'm saying replace disabling and enabling the collider with a direct physics query and running the damage code
You are not showing the crucial information that was asked for
i did everything i think i'm to stupid for thist stuff XD
Are you saying to have the Goblin Script do the code?
you think so, but we dont know, so answer the question
Just show the inspectors........
#💻┃code-beginner message
that is exactly what they said
right now your playing is checking for what is damaging it, when you want to add more damage sources you always have to adjust this script. Instead, just make a script that can deal damage and attach it to other objects
Yes
The goblin script should handle its own attacking behavior
I did so, but how should I fix the Disabling issue? Should I disable/enable the Knife Object instead?
what do you mean by disabling issue
I told you not to use disabling/enabling anything
just use a direct physics query instead of that
How should I go about doing that? I only want the Goblin to have the Attack Collider active during the end frame of an attack animation
Don't have an "attack collider" at all
Use a direct physics query every time you want the goblin to attack
use an animation event for hooking the code up to your animation
What is "direct physics query"?
things like Physics.OverlapBox
or Physics.BoxCast
Or Physics.OverlapCapsule
whatever makes sense
See options here https://docs.unity3d.com/ScriptReference/Physics.html
I'll try that. Thanks!
the game doesn't reset every time i press the spacebar but now it doesn't work at all
https://hastebin.com/share/ayamagejam.csharp
i get this error message in unity
NullReferenceException: Object reference not set to an instance of an object
LogicScript.Update () (at Assets/LogicScript.cs:34)
im assuming it means that the bird script isnt referenced at line 34 and thats why its not working but i referenced it with public BirdScript bird;
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yes because now you are seeing your real error
which is you never assigned your reference
so i fixed the problem thanks man i forgot to add the rigidbody in the script XD
Also what on earth is this:
Input.GetKeyDown(KeyCode.Space) && (!bird.birdIsAlive == false)```
It should just be `if (Input.GetKeyDown(KeyCode.Space) && !bird.birdIsAlive)`
but yeah you need to assign the bird reference properly
Yes you are struggling with the same thing almost every beginner struggles with - figuring out how references work
how can i do that?
By dragging and dropping in the inspector, usually
otherwise - see options here https://unity.huh.how/references
It works! If you were doing this, how would you approach to getting access to the Player's stats? There is no trygetcomponent with Physics.OverLapCircle
it works tysm
look at what overlap circle returns. you can call GetComponent on other components
can I make my object a child object to a "grouper" empty object without forcing the transforms to move together?
no, a child will always move with the parent. assuming you mean the grouper object is moving
Keep the parent at default transform and don't move it
is there any other way of organizing them in the hierarchy?
wait no the grouper doesn't move
Then none of the child objects will be moving due to it
it's just a folder object
oh so moving the child won't move the parent?
it is the other way around
oh ok, i thought they were tied together and being a parent was for organization in code
cool
im trying to make it so a walking sound plays when the player walks, i get no errors but no sound plays. could someone help? i wanted to incorporate the audio logic with my movement script but should i separate the two?
You should generally try to separate things over combining. I am not gonna download that file, but consider making a step event that the footstep code can hook in to. Or have the footstep script just track distance moved
oh my bad ill put it in text
using UnityEngine.InputSystem;
using UnityEngine;
public class Movement2D : MonoBehaviour
{
[SerializeField] private int speed = 3;
private Rigidbody2D rb;
private Animator animator;
private Vector2 lastMovement = Vector2.zero;
private bool hasStartedMoving = false;
public AudioSource AudioSource;
public AudioClip walkSound;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
AudioSource.clip = walkSound;
animator.SetFloat("X", 0f);
animator.SetFloat("Y", -1f);
}
private void OnMovement(InputValue value)
{
Vector2 rawInput = value.Get<Vector2>();
Vector2 movement = Vector2.zero;
if (Mathf.Abs(rawInput.x) > Mathf.Abs(rawInput.y))
{
movement = new Vector2(rawInput.x, 0f);
}
else
{
movement = new Vector2(0f, rawInput.y);
}
if (movement.magnitude > 0.1f)
{
animator.SetBool("IsWalking", true);
animator.SetFloat("X", movement.x);
animator.SetFloat("Y", movement.y);
lastMovement = movement.normalized;
AudioSource.Play();
}
else
{
animator.SetBool("IsWalking", false);
}
rb.velocity = movement.normalized * speed;
}
private void FixedUpdate()
{
if (rb.velocity.magnitude < 0.01f && hasStartedMoving)
{
Vector2 roundedPosition = new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y));
transform.position = roundedPosition;
animator.SetFloat("X", lastMovement.x);
animator.SetFloat("Y", lastMovement.y);
AudioSource.Stop();
hasStartedMoving = false;
}
}
}```
also thanks for helping, i separated the 2 but referenced eachother so i can still access when the player is moving and when the player isnt.
ohhhhhhhh
i need to use events
Yeah that's fair. You're gonna always have references somewhere.
And yeah, events are useful, but not NECESSARY. It was just an idea
thank you!
I'm currently using an array of <float, object> to list what kind of loot an enemy is going to drop. I already have 8 different loot items and I configure the array for each enemy.
I'm new to unity, but it seems to me that assigning all these values in the inspector is tedious, error-prone, and repetitive. Should I right away move away from 'programming' through the inspector and have these tables in an external file? I'm just thinking of balancing the game in the future and defining new loot types. It will be a nightmare to edit all of it through the inspector.
i would move these to scriptable objects, and let the enemy just take in a single LootTableSO. Defining them in a file will be a bit worse than scriptable objects because now you have to deal with each enemy taking in the correct array somehow. And then its also not immediately visible what loot an enemy drops
But don't you still have to configure the SOs through the inspector?
Doesn't configuring the SOs through the inspector become tedious? E.g., for balancing you have to subtract 10% of a probability of different loot items on everything. With SOs you have to click through everything and edit it. If it's in a lookup table, you at least see all the values on everything.
You could make an editor tool which would really make it easy to edit. SO would be a lot easier for seeing what loot an enemy has in inspector.
If you want the easiest solution for simply editing every loot table at once, without making any custom editor scripts, then yea whatever you use to edit a lookup table will probably be easier.
Assigning them to specific enemies wont be so fun though
I feel like making a large array with <enemyspawnid, Loot[]> in a well formatted way might provide an easier overview. Kinda like an excel table.
Now you need a link from enemyspawnid to the actual spawned prefab. It wouldnt be an easier overview because now you have to also go find what enemy is what ID
I would consider keeping a table purely for documentation purpose. In the actual game though, it's a lot nicer imo when you can just click on the enemy prefab, click on the assigned SO and see the values right there.
Also what about the case where 2 enemies share the same possible loot? Suddenly you have duplicated data, or duplicated ID
But for spawning items, you would use a factory anyways. I currently have the object factory read in all SOs and then test for a specific monobheaviour (spawnable) which contains the spawnid
Im not entirely sure what you mean by read all the SOs and test for a monobehaviour.
Maybe share code
I have a factory (a singleton) which has a serializeable array of SOs. I drag all SOs into the list. When I spawn an object, the factory goes through the list of SOs to look whether it matches the spawnid and then instantiates an object.
so guys before this script started working but now it just broke all of a sudden and the camera rotates on the X axis about 90 degrees upward into the sky
anyone might know the issue
oh and when I forcefully reset the postion to 0 while in the game the camera starts rising back up to the 90 degree postion so like it doesnt let me change i
If you're using ID, it would also make sense to throw all of these in a dictionary so you dont need to loop through it. But this is not really relevant to the talk above, about how an enemy can easily store what it can spawn
Sure, but a dictionary is not visible in the inspector (unless I buy Odin). With an array, I just select all SOs in the directory and drag them onto the factory.
The performance improvement is negligible unless you spawn often or have thousands of items.
this is what happens its having a seizure and I try to reset it to 0 but nothin
You can just have a dictionary build based off the list from editor. Theres other serialized dictionary implementations online too.
Still this whole factory part doesnt actually affect what the enemy stores. I am saying that the lookup from enemyspawnid to the actual enemy is an unnecessary step that's introduced by storing these in a file
Try just using cinemachine, itll be the best camera controller you'll have. I dont see the specific cause of your issue but theres a lot wrong with the code. Like multiplying mouse input by deltaTime and that lerp not really being used as a lerp
ive never used cinemachine do I need to keep my main camera though?
I agree that I can optimize this at runtime by converting the list into a dictionary. However, the main point was still how to store all the loot items. In a large table (ease of updates) or in the inspector ("ease" of drag&drop).
Yes cinemachine has premade controllers for the camera, you keep the main camera still
I see like 40 diffrent options which camera is the best virtual?
you can always create your own editor script for the loot tables, making it as easy as you need. Being able to keep references here really goes a long way
Or I create my own loader (instead of the editor) for loot tables and just use Excel as my editor.
🤷♂️ depends on what you need exactly, im not really knowledgeable on the different controllers they provide. try google
Up to you, I would find it pretty awful if I was working on a team project and had to edit an excel sheet for the loot table. also while having to lookup the enemy ID and make sure its the correct one. This is definitely more error prone
With an excel sheet, you do not have a hard link between enemy ID and the prefab in game. There just so happens to be an ID in the sheet that matches the ID in game.
With drag and drop, there is a hard link
I agree that spawnid typos can be annoying. What do you suggest your loot editor would look like in the inspector? I would have different SOs for different enemies and all of them have their own loot bag. Now you want to update some items in some of them. How do you effectively display this in the inspector for editing?
I havent made one myself, but you can get pretty far with an EditorWindow and finding all the SO instances with AssetDatabase.FindAssets
Right now my loot tables are pretty simple, so I wont really need to edit it much
I feel like what I'm essentially building with the loot system is a database of loot. So why not use a form of database (CSV file or another lookup table) instead of drag&drop management of individual rows in the database.
🤷♂️ if you feel its a lot easier to do, then do so. ive just given my opinions on its flaws
Hey guys, I am stuck on a problem, where currently I want to have a tmp_inputfield (password) pop up to collect input from a user when I get closer to the object (OnCollisionEnter2D), I tried using password.gameObject.SetActive(true) but it said NullRefException, I always tried using password.ActivateInputField(); and it still is the same error, am I wrong for using those lines of code or is there just some referencing problem in my code
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.tag == "Player") {
vaultText.gameObject.SetActive(true);
password.ActivateInputField();
}
}
this is the code for OnCollisionEnter2D
where vaultText is just a tip for telling user the vault is locked, and it works and does show up,
but the lower one password.ActivateInputField(); doesnt
vaultText or password is not referenced, it's null
[SerializeField]
public TMP_Text vaultText;
[SerializeField]
public TMP_InputField password;
how should I reference it then if you dont mind me asking
you don't need to make it [SerializeField] if its alerady public
you need to drag&drop it in the inspector
i did
if (collision.gameObject.tag == "Player") {
Debug.Log($"Vault text: {vaultText}");
Debug.Log($"Passowrd: {password}");
vaultText.gameObject.SetActive(true);
password.ActivateInputField();
}
show the debug logs
Vault text: vaultTip (TMPro.TextMeshProUGUI)
UnityEngine.Debug:Log (object)
vaultTip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/Script/vaultTip.cs:26)
Password:
UnityEngine.Debug:Log (object)
vaultTip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/Script/vaultTip.cs:27)
NullReferenceException: Object reference not set to an instance of an object
vaultTip.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Script/vaultTip.cs:29)
what is line 29
password.ActivateInputField();
the password is null
do you see a reference to password in the inspector
in runtime?
public void Start() {
vaultText.gameObject.SetActive(false);
vault = this.GetComponent<BoxCollider2D>();
password.DeactivateInputField();
password = this.GetComponent<TMP_InputField>();
}
yea, you dont mix it
you either drag&drop it in the inspector
or you reference it in the start/awake
unless you know what you're doing
pretty sure you can write a small editor script that will show dictionaries in the inspector, without an additional purchase.
you can use GenericDictionary from github
it's free and CC0 license
and it looks like this (this is GenericDictionary<enum,Vector2>)
!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.
using System.Collections.Generic;
using UnityEngine;
public class ProjectileScript : MonoBehaviour
{
public Rigidbody2D theSeedBrain;
public float deadZone = -17;
public float timer = 0;
public float coolDown = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < coolDown)
{
timer = timer + Time.deltaTime;
}
else
{
addSeed();
timer = 0;
}
if (transform.position.y < deadZone)
{
Destroy(gameObject);
}
}
public void addSeed()
{
Instantiate(theSeedBrain, new Vector3(0, -2, 0), transform.rotation);
}
}
``` Why my code doesn't work
Wdym by "it doesn't work"? What are you expecting it to do and what does it do instead?
well why when the timer reach 5 it doesn't Instantiate the object
I have tried Everything i cant get the game over text which uses text mesh pro to pure white or any other light colors.
Add debug.Log to see if that code is ever running
This is not a code related question
where should i post it?
Nice to see they posted where told to.. #💻┃unity-talk message 🤦♂️
Someone please help me! My hand colliders was working but it won't anymore. When I make my hand press a button it doesn't work anymore which is strange.
delete from here and ask in #🥽┃virtual-reality
hello
I recently returned to Unity and since then I have had a lot of bugs since the new versions
How do I make a multiplayer systeme with 1 player that can host a party and another player can join by entering his ip adresse
#archived-networking and that's called P2P - Peer-to-Peer
Okay
I'd also recommend starting with a single player game.
ok
you haven't assigned the rigidbody, but you're trying to use it
Another question how to make when a collider touch another collider this one goes in the other direction
or in my script or inspector
yes
Use OnCollisionEnter to detect the collision and run your logic.
Assign the rigidbody as the error clearly indicates
This is not related to your code but instead the editor inspector
thank you, and how do I do it in the inspector
This is really basic stuff, you need to go to !learn and follow the beginner tuts
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
OK GREAT THANK YOU GENTLEMEN
Hi So i am using emmision color to give a glow effect to my lights.But i want to switch up the lught in code.I can just use the Color to switch up the albedo but how do i mention the emmision color so the color of the glow changes
I had my file dragged into the other one, sorry, I didn't see it. No more error message when I don't put it I still can't move my character.
That sounds like a different issue
Consider logging the rigidbody's velocity after you update it
So if you have a reference to the material, you need to adjust the "_EmmisionColor" property. SomeMaterial.SetColor("_EmissionColor", Color.blue)
Docs: https://docs.unity3d.com/ScriptReference/Material.SetColor.html
Thank you
OK, thank you very well that's just it, it works thank you
!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.
void Update()
{
StartCoroutine(ChangeColor());
}
IEnumerator ChangeColor()
{
yield return new WaitForSeconds(3f);
CurrentColor.color = CurrentColor.SetColor("_EmissiveColor", Color.Lerp(CurrentColor.color, colors[Index], time * Time.deltaTime));
Index +=1;
}
void ResetIndex()
{
if(Index == colors.Length)
{
Index = 0;
}
}
}
Want to do this but theres an error
Color.Lerp(CurrentColor.color, colors[Index], time * Time.deltaTime));
This line
So share the error
I would guess SetColor returns void
yea
Yeah why are you doing Color = SetColor
That doesn't make sense
I would expect one or the other
oh wait it shoul be nothing there
Basic c# questions like these can be avoided if you just learn c# before you even consider using Unity
This channel is not for these things
number = Random.Range(1, 2); will the number be 1 or 2 ?
This will always return 1
Read the docs
my b i just did the error cus i was in a rush sry
Always read the error properly because most of the time it clearly explains the issue
I just did something very wrong cus unity just crashed when the code was supposed to be run
-> in a rush
-> posts to discord taking longer to get the answer than would have if the error was read properly
I'm creating a game, and would love to invite other people onto the project. But what is the best way to colaborate with other people and manage all the code? Google is sending me in so many directions that i'm honestly lost on what to actually choose (Github, Unity Teams, Unity DevOps, Unity Cloud, Perforce, ...).
What exactly should I be looking into (Free would be preferable)
Git/GitHub is widely used
I'll just use that then, thanks
{
transform.position = Vector2(0, 0);
}``` Why is this incorrect
you are missing the new keyword. Alternatively use Vector2.zero
oh ok
Why can Unity not serialise nullable enumeration constants?
i.e.
[SerializeField] private DiceType? _requiredDiceType;
Simple answer, because their serializer is crap
Lool
just use classes :)
{
if (collision.gameObject.layer == 3)
{
circle.initiPos();
circle.leftOrRight();
Debug.Log("YeaRunning");
}
}
}``` ```public void initiPos()
{
transform.position = new Vector2(0, 0);
}``` Why the circle don't go to the position
Yes the debug log is printed
then the initiPos() is called aswell on circle instance
public void initiPos()
{
transform.position = new Vector2(0, 0);
Debug.Log($"Position: {transform.position}");
}
show that debug log
Position: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
CircleLogic:initiPos () (at Assets/CircleLogic.cs:20)
Points:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Points.cs:24)
then it is 0,0,0
and the method works correctly
you are probably overriting the transform.position somewhere else
maybe
i installed the input system package. in my script, i initialized a var: "public InputAction cameraControls;". back in the editor, i added a "CameraHorizontal" action and bound it to Negative/Positive. then i enabled it "cameraControls.Enable();". but how do I access this action?
I corrected the script
does another edit the circle position? what position is the circle at?
My code was wrong beause I forgot that the script wasn't in the object that's why it didn't worked
How do I change the name of a script ?
change the name in Unity, then update the class name in the script . . .
ok
i dont know how to phrase it
but pretty much Script B is still called when its not supposed to
because of the order
which causes me to drop an item im holding
both codes run in Update. unfortunately, you can not determine which update runs first (unless you change the script execution order for both scripts, so that script B always executes after script A) . . .
use the script execution oder to set which script runs before the other . . .
whoa, a question about date time or smth just disappeared . . .
would i still get this issue if i used the new input system?
would there be a way around this?
you'd still send the key down input to both scripts . . .
i don't know what you're actually trying to do, so i can't say what a fix would be . . .
its hard for me to explain
Why not add a &&inventoryIsOpen check to the shoulder part ?
If you want to drop from both states with G
how to change size of list with code?
How to make that the ball don't go just on the x axe and how to make that the player don't slide until it hit a collider
{
if (Input.GetKeyDown(KeyCode.W) == true)
{
player1.velocity = Vector2.up * speedUp;
}
if (Input.GetKeyDown(KeyCode.S) == true)
{
player1.velocity = Vector2.down * speedDown;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true)
{
player2.velocity = Vector2.up * speedUp;
}
if (Input.GetKeyDown(KeyCode.DownArrow) == true)
{
player2.velocity = Vector2.down * speedDown;
}
}```
well how do you move the ball?
{
rNumber();
if (right == true)
{
circleRig.velocity = Vector2.right * circleSpeed;
}
else
{
circleRig.velocity = Vector2.left * circleSpeed;
}
}
public void rNumber()
{
number = Random.Range(1, 3);
if (number == 1)
{
right = true;
}
else
{
right = false;
}
}```
you only move it left and right, to move it up and down i assume you need to transfer the velocity of the paddle to the ball instead of just setting one velocity
ok I will try
adding or removing an element will expand or contract the list; or reinitialize the list with a set capacity . . .
I can change the list size manually. I want to do this with code. I know what you said, but no matter what I did, I could not increase the size of the list or add empty elements with the code.
is that an actual list or an array? show the code . . .
you can add elements to the list with code, but an array is a set size . . .
but you can change the size of an array from the inspector . . .
public class ItemDatas
{
public List<ItemData> dataItems = new List<ItemData>();
}
this is a list
it isn't an array
add a null reference in Start and check if it changhes . . .
In code, to change the size of the list, you add elements to it. Setting the size to a specific number is a convenience unity provides in the inspector but under the hood it just calls Add several times
also, you never showed what you did. it was probably incorrect . . .
how to make when I add velocity to an object it doesn't go in the direction without stoping
"going in a direction without stopping" is pretty much the definition of velocity
if you want it to stop, change the velocity again
for(int i = 0; i < 210; i++)
{
itemDatas.dataItems.Add(null);
}
or add a force in the opposite direction
ok
It worked when I used for and null reference, thank you
you make it stop/slow, so reduce the velocity
you have to add smth to the list. null is an empty reference, though, if you wanted a set number, just initialize the list with a capacity/size and it'll do that for you . . .
Can you show it with code?
Initializing a list accepts a single integer as a parameter which indicates the size
Same as how any other constructor works with parameters
{
player1.velocity = Vector2.up * speedUp;
}
else
{
player1.velocity = 0;
}```Why it don't work
You're going to have to explain more about what doesn't work
the else part
Consider logging the player's velocity and seeing what happends to it
Also consider logging the GetKeyDown statement and see if this gets called
As in, check if the actual method returns true/false
You'll need to fix your compile errors
player1.velocity = 0; this doesn't make sense
so how do I make that the velocity stop
public class ItemDatas
{
public List<ItemData> dataItems[210];
} This isn't work
public class ItemDatas
{
public List<ItemData> dataItems = new List<ItemData>(210);
} This isn't work
void Start()
{
el = Player.GetComponent<El>();
er = GameObject.FindGameObjectWithTag("Envanter").GetComponent<Envanter>();
/*for(int i = 0; i < 210; i++)
{
itemDatas.dataItems.Add(null);
}*/
itemDatas.dataItems.Capacity = 100;
StartCoroutine(ItemKaydetme1Cor());
} This isn't work
Share you code in a readable way !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.
and explain what "isn't work" means exactly.
What should I do to make empty instead of null value?
make what empty
ok wait a minute
I want to change the size of the list with code. I don't want to enter values manually.
What you have would work but really you should be using an array not a list
This adds it but as a null reference I want it to be added as empty
there is no other "empty" other than null
for a reference type like this
use an array sir
for(int i = 0; i < 210; i++)
{
itemDatas.dataItems.Add(null);
}
Yes I saw the code
you don't need to show it again
Again you should really just use an array
ItemData[] items;
void Awake() {
items = new ItemData[210];
}```
no need for a loop
I understand, thank you, I will try what you said.
Hi, I'd like my character to fire a projectile at the target (the player) and move towards it. I've tried to do this but if I ever give my projectile an angle and apply the direction projectile.transform.position - target.transform.position then the arrow no longer goes in the right direction, if I remove the angle it goes in the right direction but is turned the wrong way. (I'm working on a 3D project)
what I've explained is from the enemy's POV
Bro I thought the only way to move the player is to use velocity💀
Here's all the main ways of moving
There are more too
You have any more of those that help with decision making? Because damn I love me some diagrams
Not made by me, made by Hariedo from the Unity Developers Community server
Creating my class diagram but I'm getting a feeling that my thinking is going to create some problems later on. Any feedback? (Still WIP btw)
Basing my game on kingdom new crowns, if that makes it easier to give feedback
@queen adder Please don't crosspost. Also this is a programming channel.
more organized than I've ever been.
good stuff.
Ok
where'd you post from?
cheers
Hello, I don't know if it's beginner question or maybe general / advanced, but I need help with chunks or cache.
I have tilemap 1500 width x 600 height. I created loading system which is loading all data between player position + and - 150 tiles every 5 seconds. It's ok when it's not unloading anything, but when it's going to unload tiles then it's lagging short amount of time, but still lagging. Video and picture should help to understand my problem.
The question is - how to optimize it more, remove unloader or it's possible to do it better? Maybe make similar option like load method has?
Why do you even need to load/unload the tiles?
When I loaded all the tiles my ram goes high and unity wasn't going smooth.
Laggs everywhere.
Did you actually test and profile?
Are you using the unity tilemaps?
Yes, unity tilemaps modified by extending TileBase.
Tiles outside the camera frustum aren't rendered, so they shouldn't contribute to lag. And ram shouldn't be a problem. You're probably holding the "unloaded" tiles in memory anyway.
Basically, it's a classical case of premature optimization
Well, it's 2 dimensional array with enums.
After player destroy block it's saved to array with null.
If player place any block - enum with tile information
I mean, if you're planning to have an infinite level, that might be needed, but if you have a limited map, I'd just have it all in the tilemap at the same time.
Anyways, the answer to your original question is the same: profile the game to see what exactly causes the lag spikes.
Ok, I'll try profiler
It will be limited map, but after loading entire map it caused lag, maybe your option will tell me more.
Capture some profiler data when the whole map is loaded and share. Then we can talk.
Though, I'm going to sleep soon, so maybe someone else would be able to help you.
good night :)
Not too sure what set tile operation consists of, but you could always just load little by little instead of by loading by large chunks.
or do some lazy loading
@timber tide I already did it, when I loaded entire map it took like 4 GB, when I loaded parts it took only 100 MB.
feels like the issue lies elsewhere though. It shouldn't be very intensive just to have those things on screen no?
4GB goddamn
nevermind.
When I made map bigger, like 5000x2000 it took 8 GB
what are you LOADING?
Tilemap 😄
Havent really used unity's tilemap but this is why you chunk
Tilemap took everything, and it's only loading script.
And it's why I made loader part by part.
Please check the video, it's after split load.
is it a terraria-type environment you're making?
Yes.
Hello, my raycast doesn`t work
// 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)
{
animator.Play("BlackWerewolfWalk");
GetComponent<SpriteRenderer>().flipX = false;
}
else if (h <= -0.1)
{
animator.Play("BlackWerewolfWalk");
GetComponent<SpriteRenderer>().flipX = true;
}
else
{
animator.Play("BlackWerewolfIdle");
}
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
// transform.position = new Vector2(transform.position.x, transform.position.y * jumpForce *Time.deltaTime);
rb2d.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
Jump();
}
void Jump()
{
Vector2 startPoint = transform.position;
Vector2 endPoint = Vector2.down;
float rangePoint = 0.1f;
RaycastHit2D hitGround2D = Physics2D.Raycast(startPoint, endPoint, rangePoint);
if (hitGround2D.collider != null)
{
if (hitGround2D.collider.CompareTag("Ground"))
{
isGround = true;
Debug.Log("Ground");
}
}
else
{
isGround = false;
Debug.Log("Jump");
}
}
}
use Debugging in VS
check where the raycast is going
use gizmos to see in the scene where the raycast is going
Clear too
What?
Debug.DrawRay(hitGround2D);
more like Debug.DrawRay(startPoint, endPoint, Color.blue, 5f);
something like that
if it happens in Update you can remove the 5f
maybe Debug.DrawRay(startPoint, endPoint * rangePoint, Color.blue, 5f);
that gives you the raycast you're doing.
keep in mind 2D ignores z to some extent.
I think your raycast isn't working because of the direction...let me double check
Yeah it takes a position+direction not two positions
Nvm it is a direction, you just named it point
Oh I'm dummy yeah
Any suggestions for keeping track player aggro, total damage dealt, and other metrics in a multiplayer game?
When you deal damage to an enemy or become detected by it, id like to see if its registered to a list and record metrics.
Keeping track of things like total damage dealt would be important for things like qualifying for item drops, while aggro could fluctuate and probably be reduced by a % on an interval.
Would it be dumb to use a nullable data type as keys in a dictionary?
For instance dictionary where key is reference to player networked object, and value would be context info
What would be the benefit of that?
So that you can easilly check aggroList.Contains(playerId) when you are handling detection checks and things lk that
Might be better to do it manually and loop through
but why does it need to be nullable?
It doesnt exactly need to be,
I like using a reference to their NetworkIdentity component to easilly handle things on the server side
Using mirror in my case
Theres no guarantee that the gameobject might get destroyed though
Or moved to another scene
definitely just use the int playerId or whatever as the key
I believe I can do that with NetworkIdentities in mirror
a nullable int would mean your key is... null? Which means you have no idea what player it's for.
Havent had to til now though
Well yeah, that would be a case where I want to ignore/remove them from the list
void Jump()
{
Vector2 startPoint = transform.position;
Vector2 endPoint = Vector2.down;
float rangePoint = 0.1f;
RaycastHit2D hitGround2D = Physics2D.Raycast(startPoint, endPoint, rangePoint);
if (hitGround2D.collider != null)
{
if (hitGround2D.collider.CompareTag("Ground"))
{
isGround = true;
Debug.Log("Ground");
Debug.DrawRay(startPoint, endPoint, Color.green, rangePoint);
}
}
else
{
isGround = false;
Debug.Log("Jump");
Debug.DrawRay(startPoint, endPoint, Color.red, rangePoint);
}
}
Only green
Then your raycast is always hitting a collider.
Also, endPoint is not a good name for what is a direction and not a point
I don`t understand
Ok, i`ll change
rangePoint is also...? why not just range?
Your debug ray draws as red when the raycast doesn't hit anything. If you never see a red ray, then you're always hitting something
I`d like to write a lot of range
wat?
But i`m jumping
Try logging the value of hitGround2D.collider inside of the null check. See what's being hit
I`ll have a lot of range
Again, wat?
I'll say it again, what?
what does tha thave to do with the name of the variable rangePoint?
Range for weapons
I don't know what you mean by this
rangePoint is not a point. It should probably just be called range
Ok
if (hitGround2D.collider != null) { Debug.Log("yes"); }
else { Debug.Log("no"); }
how does that help
I`m checking
You are just logging the words yes and no
Which is useless
I told you what to log. Log something useful, not just a word that tells us what we already know
if (hitGround2D.collider != null && hitGround2D.collider.CompareTag("Ground"))
{
Debug.Log("Hit Ground: " + hitGround2D.collider.gameObject.name);
}
This?
Why are you now combining the if statements
we specifically are trying to find the thing that isn't ground that you're hitting
this, again, doesn't tell us any new information
I don't understand what you mean
If you hit something, log it
That's it
Don't have the && part
don't check for anything else on the object
just unconditionally log the thing the raycast hits
I literally told you exactly what to do. Why did you go and change everything else?
so log the thing it is hitting like I said
I don`t know why
And you never will until you actually check what is happening
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 10f);
if (hit.collider != null)
{
GameObject hitObject = hit.collider.gameObject;
string objectName = hitObject.name;
Debug.Log("Hit object name: " + objectName);
}
}
Sure, there you go, but why is this a completely different ray than the one you were already using?
This is going to tell you what this ray is hitting but that's not the ray you care about so why are you checking this one?
So whatever ray you've put this log in is hitting BlackWerewolf
What do you mean "that's not object"
so, the ray is hitting your character instead of the ground then?
you would want to seperate layers, so that the ray ignores your character
In inspector?
every GameObject has a Layer, and it's used for many things
in this case you'd use it to ignore the physics of the player when raycasting.
Create a layer called "Player", and make sure the raycast uses a LayerMask.
Better to make a "Ground" layer and have the raycast look for specifically that
also works. Might want to do both.
personally don't do that very often actually, I just stick with default nowadays. It was too much of a hassle making anything that I want to be physically involved in the game into a layer instead of just leaving it
found that I more often wanted to interact with things than not ya know?
it's... lost?
I don`t see its
Went to the supermarket
Maybe
This isn't a layer
you mean the Debug.DrawRay?
Yes
strange... maybe it only runs when the raycast hits something. Make sure it runs every Update regardless of what happens.
either way, google on how to set up LayerMasks with raycasts and objects - it's very useful to know :)
if (hitGround2D.collider != null)
{
if (hitGround2D.collider.CompareTag("Ground"))
{
isGround = true;
Debug.Log("Ground");
Debug.DrawRay(startPoint, endPoint, Color.green, rangeWerewolf);
GameObject gameobj = hitGround2D.collider.gameObject;
Debug.Log(gameobj.name);
}
}
else
{
isGround = false;
Debug.Log("Jump");
Debug.DrawRay(startPoint, endPoint, Color.red, rangeWerewolf);
}
Debug.Log doesn`t work too
You just found out that your ray is hitting the werewolf. The werewolf is an object, so the red ray doesn't get drawn. The werewolf is not tagged "Ground" so the green ray is not drawn. So, why were you expecting any ray to draw?
But raycast hitting square
No, raycast is hitting werewolf. We literally just checked that
that was the whole point of the log
put the Debug.DrawRay in front of the first if
have it always run
don't put it behind an else
Doesn`t work
also, due to how raycasts work (at least the one you're using), it stops after it hits anything.
What's happening is that the ray is hitting your character (because it starts inside it), and never continues towards the ground.
In what way doesn't it work
It should hitting the ground
But doesn`t work
What?
I told you why.
Do you have any idea at all what you're doing
you need to use Layers.
You seem to be ignoring what everyone is telling you
Ignore the player with the raycast.
Just raycast
Ok
see, now we see the beam again.
I`ll watch
Oh hey look exactly the thing leo said would happen is happening. The fuck you mean "doesn't work"
it's working right there
see how the beam starts inside the player?
the red ray is visible
this means that the player is being hit.
Already
Because of this, the ground is never hit. The player is blocking the ground.
The thing they told you to do was to move the red ray so you can see it
And now you can see it
That should be ok. Rays cant hit stuff from the inside by default
Unless 2D is different
Pretty sure 2D rays can, since the collider is actually just the edge lines
I think it is.
I see
@wraith valley Do you understand what's happening?
The red line starts from the top and ends at the bottom. The thing is, it's not actually what your raycast is doing. As soon as the player is hit (the ray starts from the player, so it's instantly hit) the raycast stops traveling.
It never hits the ground, because the player is in the way. You need to set up LayerMasks to fix this issue.
So using getname isn't working very well for me:
enum colorPiece {dark = -1, light = 1};
[SerializeField] int startSide;
void Start()
{
color = (colorPiece)startSide;
kingFolder = new GameObject(System.Enum.GetName(typeof(colorPiece), color) + "King Folder");
}
You see, right now your issue is you're trying to teach them how to debug something, but they are literally just waiting for someone to write the code for them. So when you provide any code, they assume it's a solution to the problem rather than the next debugging step
I want it to say dark king folder
Ok, player sprite covering byself?
Yes
so the raycast hits the player, and then stops.
But collider without tag Ground
It's like a lazer pointer, it doesn't go through objects, it stops when it hits them.
yes, but tags are different from LayerMasks.
Tags are a type of name for an object. A LayerMask actually affects the way physics works on objects
the issue is that we're hitting the player ->
then we check for the tag on the player
And what did you do here?
we don't care what the player's tag is right? We want to know about the ground below the player.
Testing
Are you sure startSide is the value you expect it to be? If it's not -1 or 1, then it's going to be blank
Already working
That explains nothing
But werewolf under ground
@wraith valley Do you understand why it's working now?
You can see where the ray is yes?
Ok
Yes
the ray isn't colliding with the player anymore, so it checks the ground like we want to
Collider don`t colliding with ray
the thing is, we don't want the werewolf underground right?
I mean this
Is the ground set to the ground layer?
yes!
no layers involved yet, I'm trying.
What?
LayerMasks Brian.
Ah, I thought you switched from tag to layer
I want him to.
YES!
You need to google a guide on layers and layermasks. The docs are good. Maybe look up a video too
exactly this
This so hard
I`d rather to watch video
Unfortunately you are going to need to learn how to read to code things
But with raycast is better in Unity Learn
that's good that you read and understood that, nice
I know
LayerMasks are a bit more complicated, but I'm sure you'll get the hang of it
https://www.youtube.com/watch?v=uDYE3RFMNzk
Watch this all the way to 7:30 and you should have a better understanding :)
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=uDYE3RFMNzk
Let's look at Layers and Bitmasks to see how they work. We can manipulate Physics interactions and what a Camera sees.
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials https://...
Thanks
it covers all three things you need to know.
Oh...🗿
yeah, that's a part of it. I think he mentions it in the video.
yeah it's assigned in the inspector. I multiply the position value by the startside to get the starting locations, and they end in the correct spot
Maybe log color after you get it from startSide? See if it's parsing that into the right enum value?
do you want it to say "Black King Folder"?
No, dark, the name of the enum
what digiholic just said, my bad...
In C#, is there a way to automatically have a class create an instance of itself?
This is my current version, which is rather error-prone, and it feels like there must be a pattern that does it better:
public void StartNewGame()
{
_serviceManager = new();
new ActionService();
new CombatService();
new MapService();
new PlayerService();
new RNGService();
new GameTaskService();
new GamePhaseService();
new TurnService();
_serviceManager.InitAll();
}
It's definitely the assigning to the color
Hm, there's some 0s in there
maybe the cast was wrong?
those would end up being blank
yeah the start side is correct but the assignment to color turns to 0
wait the assignment nees to be befors instantiatefolders my b
got it, the color=(colorpiece)startside needed to be done before the initialize pieces call
not if the method is not running..
it should be
the animation does play
i can see it playing
but the landmine stays inactive
the script should be on the same object as animator, and if you select the actual instance running that animation you will see dropdown of methods
also whats up with that internal landMine is probably null too
it shouldnt be null
also ye it has both
here is full
its their spawner
wait
nvm i think i know the problem
Hi, I encountered this problem..., I tried to replace the "collisionInfo" with "triggerinfo", and unsurprisingly it didn't work. May someone help me? Thanks
wrong signature for that parameter
Have you looked at OnTriggerEnter code examples?
You're missing the parameter for the method
also the parameter would directly be the collider for this
From a basic C# standpoint - you can only use variables that exist in the scope 😄
the issue was that i had forgotten a previous attempt where basically i had it disable the landmine in update lol, anyways solved 👍
Btw you should use this method for tags instead of ==
https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
it even has proper example with Trigger
Thanks
IEnumerator WinSequence()
{
if (lastPlace != null)
{
Character player = Instantiate(lastPlace.character.characterPrefab, lastPlaceSpawn.position,
Quaternion.identity).GetComponent<Character>();
InitPlayers();
player.playerShape.material = lastPlace.character.color[lastPlace.controller.colorNum];
yield return new WaitForSeconds(1);
}
Why is this code block running when last place has nothing in it?
I guess Last Place itself isn't null - because it seems to be a container of some sort. Does that sound right?
it looks to be from the inspector at least.
last place and the other places are of type Win character
public class WinCharacter
{
public CharacterInfo character;
public MatchPlayerData match;
public PlayerInputController controller;
}
last place is not null
its serialized in the inspector
oh wait i see yeah
so the WinCharacter itself actually exists, but you need to check WinCharacter.character != null
is it because of this?
Unity will automatically do new() on POCOs embedded(public/serializefield) as Serializable
just check character?
if(lastPlace.character == null) return
okay that makes sense too. also what is POCO?
plain ol c# object or class object
oh lmao
like class/struct are pocos
So I dont know if this is allowed here but im at my wits end. If i make a public field in a script that is inside an animator. So an animator object, why cant I drag anything into it?
it wont let me drag any of my animators into it
and its really driving me up the wall
I did ask in #🏃┃animation but that chat is dead rn
What exactly are you trying to drag into those slots?
Animators
from where?
my hierarchy. Objects that have animations on them
Objects in assets cannot reference scene objects. The animation clip is an asset like a prefab, and it can exist in any scene
Assets cannot reference scene objects
ah right. How do i get around that then?
Since this is a StateMachineBehaviour (right? that's how scripts attached to animatins work I think?) you get access to the Animator in every single callback in the StateMachineBehaviour
How do I change a param in another animator in this animator
if i cant reference it
I don't understand what that question means
I have other animators that I want to reference so I can change their parameters
You get the animator reference in the callbacks
not the current running animator
for the animator this animation is attached to
other ones
You'll ahve to get the reference programmatically somehow
Either by proxying through some other script attached to the object
or some other way
if you want to set it in the inspector, using a proxy MonoBehaviour may be the easiest thing
For example:
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
MyProxyScript ex = animator.GetComponent<MyProxyScript>();
Animator someOtherAnimator = ex.SomeAnimator;
}```
I dont understand "MyProxyScript". What type would that actually be lol.
oh wait thatd be a new script or smth
cos its a class type
A script that has references to the animators of other objects you want
It's an example. It would be a new script you'd write that has the references you need.
It would derive from MonoBehaviour
Not a code question
dangg
Sorry for dumb question. But Deltatime is only for small numbers right? Not for whole/big numbers. like 7.
It's tied to the framerate. If your game freezes for 7 seconds, it will be 7
The thing is, i have a counter which uses deltatime and it goes like 0,500 (for example) and i need it to go like 1,2,3,4, etc.
(delta time is the time in seconds elapsed since the last frame was rendered)
im trying to make a grappling hook but when it hooks it just makes the character spin i cant figure out why
using UnityEngine;
using UnityEngine.UI;
public class Controller_Hud : MonoBehaviour
{
public static bool gameOver = false;
public Text distanceText;
public Text gameOverText;
private float distance = 0;
void Start()
{
gameOver = false;
distance = 0;
distanceText.text = distance.ToString();
gameOverText.gameObject.SetActive(false);
}
void Update()
{
if (gameOver)
{
Time.timeScale = 0;
gameOverText.text = "Skill Issue \n Total Distance: " + distance.ToString();
gameOverText.gameObject.SetActive(true);
}
else
{
distance += Time.deltaTime;
distanceText.text = distance.ToString();
}
}
}
If you need it to go faster, multiply the value by another number. Like 2, to go twice as fast
(2 per second)
oh. i did not thought of that. thanks.
not sure how i can do that tho, but ill try i guess.
Your current code will increase distance by 1 each second while you're not in a game over state
+= Time.deltaTime * 2 for 2 per second
Can someone help me out please. I attached a script for movement of my airplane. For some reason, after I do a couple of spins (line 90), my airplane starts to shake a little on turns. Also, sometimes spins perform weirdly if i am doing them during turning (line 146, line 228).
You appear to be mixing Rigidbody motion with directly moving and rotating the Transform
how do i keep it from spinning all arround
that's a no-no
how should i approach it?
oh nevermind your Rigidbody is kinematic?
spin what
yes
my player
you know you don't have to disable gravity if you make it kinematic. Gravity won't affect the kinematic body anywat
it like uses the grapple then spins arround after it grappled on to something
oh, okay, will delete it (gravity line)
so how is this image supposed to help others help you
mane you know im dumb
ill send the code 1 sec
Are you asking how to prevent your Rigidbody from tilting over?
https://gdl.space/ayirizegeb.cs grappling gun
oh spring joints are tricky
is this from a tutorial? but yea might need to lock rotation maybe on rb
any idea what can cause that?
well, your code of coursew
which is quite long
and involves a lot of weird/adhoc improper Lerping etc
improper?
yeah it is how do i lock rotation
Like you're doing a lot of stuff like smoothYawChange = Mathf.Lerp(smoothYawChange, yawChange, yawSmoothing);
there are constraints on the rigidbody component, but idk if you're supposed to brute force it
which is not going to be framerate independent and may certainly cause jitter etc
that's not really a "correct" usage of Lerp
I removed lerping, but the problem persisted.
i just wanted to smoth it a little.
this isn't a code question
you are just asking how to constrain the rotation of your Rigidbody.
Do so in the inspector for your Rigidbody under "Constraints"
ok
how can i chenge the shape outer spot in code
Light API reference: https://docs.unity3d.com/ScriptReference/Light.html
my game has a respawn, when the player dies it doesnt have a follow anymore on my cinemachine, how do i freeze the cameras movement till he respawns?
currently i am getting movement when he dies, i dont want that
just disable it
thank u, worked, im stupid sometimes!
if invoke is called several times before it manages to run the method it is invoking with it still invoke it 3 times or once?
it will invoke as many times as you invoke it
alright thanks
How can I modify a rigidbody's velocity to approach a specific magnitude value of maxForce? Should I be using AddForce? How would I do the calculation?
how does one invoke a method but its through a reference like spawner.Spawn() but invoke it and make it run in 1seconds
put the timed method inside that one
spawner.Spawn()
void Spawn() { Invoke(etc..) }
i make a method that runs spawner.Spawn() then invoke that method?
You want something in spawner to run after 1 second?
yes to run the Spawn() method in spawner after 1 second
I would put delay on the spawner itself
using a coroutine
public void Spawn()
{
StartCoroutine(SpawnDelayed(1));
}
IEnumerator SpawnDelayed(float time)
{
yield return new WaitForSeconds(time);
//do stuff
}```
what does it mean to delay the spawner itself? 😟
huh? I said put the delay in the spawner script
oh i meant that Spawn() is in script A and im running it in screipt B
oh
i get that
either way you can do it, you can also put delay in script B 🤷♂️
You can reverse it
private void CallSpawnDelayed(){
StartCoroutine(SpawnDelayed(1));
}
IEnumerator SpawnDelayed(float time){
yield return new WaitForSeconds(time);
spawnerScript.Spawn();
}```
i use the Spawn() method in antoher way as well do if there is a solution to not change it id rather do that (cuz also i have 12 spawners that would need to be changed)
if you explained what you're trying to do or why you need delay it would help offer a suggestion
basically, a timer n a bunch of rng stuff happen
if they all are right
return true
then the method decides wat type of projectile to fire
but i dont want it to spawn at that exact moment
otherwise the spawns will be in bulks
so i wanna space em out by 0 - 1second (thats the return value of SpawnDelayer())
Put the loops inside a coroutine and use yield
but idk how to invoke the spawner.spawn()
Is there anything inherently wrong with using a static FSM for my game states?
You don't even need that just learn coroutines
what do you mean by "static FSM"?
hmm alright
A finite state machine that deals with my game states. I don't need multiple instances of that FSM, more like a singleton.
Is it okay to make the FSM public and static? I can't think of a way to encapsulate it
generic state machine?
shouldn't an enum suffice for a game state?
What's wrong with the typical Singleton pattern?
the code for adding to the singleton works fine, the code for removing it leaves an empty gameobject
Not in my case. that really isn't the question though, since I have my FSM and it works. I am just wondering if my FSM/Enum should be public or if I should encapsulate it from a design perspective
what do you mean by "leaves an empty gameobject"?
which object is left?
Which object is this script on?
hi, im having dificulties understanding how to acess a script in my game, im working on a enemy ai that uses a StateMachine, the enemy object uses a script for its ai that calls other scripts that are its states, being a patrolState and a attackState, im having dificulties in the attackState script being called, the way its supposed to work is by a canSeePlayer method that uses a ray to detect a player, i have run various debugs log, and it should work since it has all the requirements for the attackState to be called, but i dont really know what to do, these parts is where i think the issues are https://paste.myst.rs/3y6ymz3b
a powerful website for storing and sharing text and code snippets. completely free and open source.
Nothing. It's if the FSM states should be accessibly publicly
Are you sure destruct() is running?
the node holding the script is the same node trying to remove itself from existence
Use the singleton pattern then
which does include a static reference
use property with private set
that's fine
yes, it's the only place in my scripts where Destroy(gameObject) could be getting called
Nonetheless - Debug.Log as always should be the first step.
So like a property as navarone suggested?
sure a static reference property
though personally would Invoke an event when statechanged and broadcasting the enum
thank you
Could you explain exactly what isn't working here?
Found the problem, destruct() was running in two scripts, I added my console.log to the wrong one. Thank you, should have asked my partner which script he logged when he showed me
i have an attakState and a patrolState, im having dificulties in transitioning to the attcakState
You are going to need to get way more specific than "difficulties"
it doesnt transition to an attackState, previously i had it working, but i then started to implement another enemy type in the stateMachine.cs wich is responsable for mojoraty of the logic between transitioning from a state when requirements are met, such as a method for seeing the player wich in varios debugs i ran shows its true and a method for the transiotioning wich also comes has true, the problem im having is its not going into the desired state wich is the AttackState
stats.DOMove(new Vector3(208, -374.2f, 0), 1)```
why is this sending it here?
stats is a rect transform
Is the object a child of something else?
try DoLocalMove
InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <2acbecbc299e4654adc94df891af51f2>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <65927d60dd5f4df5850222879a8ed9a4>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <546dbfe4aa3a47b4a64849b03910c33f>:0)
I get this error code approximately ten percent of the time when destroying a turret object, but only when the inspector panel for a singleton keeping an array of all turrets is open
thats fixed it thank you
that error is from the inspector
hi guys, so im working on a 2d adventure game and ive got down the basic movement, camera follow, and i tried adding a heart system and it shows the heart and everything but when i enter game mode the hearts are nowhere to be found, this is my scene and health scripts:
so I don't need to do anything beyond "don't try to inspect the singleton while deleting stuff?"
or is it going to cause big problems later because something at the core is wrong?
why did you put the health script on each individual heart?
It should be on only one object.
oh nvm it's on the player
are you sure it's not on any other objects?
also show your game view
Yeah i think it's just a bug in the editor
Also if your !ide always looks like this, it's unconfigured
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
ok sry for not responding was rewatching video to see if i missed something but i didnt:
ok ill do that
yea it's only on the player nothing else
in the video his shows up in the top left when he enters game mode
is this while the game is running? Or at edit time?
you cropped the window so it's hard to tell
thats while running
Ok so show those hearts in scene view when it's running. And also show their inspectors
i started playing around with the size of the hearts and they appeared but their still incredibly small
this is not anything that I asked to see 😦
I asked to see their inspectors too please!
select them
i've never used UI before so i didnt know how big to make them
since you cropped your screenshot they're probably here you just cropped them out
Resize them until they look good in the Game window
you can open game and scene windows side by side if you want
ok ty
am i like on the right path here? i pass in the script but then calling it.. idk how
im curious what value_projectiles is
make the function itself a coroutine and yield inside loop
What the hell
why is the parameter of type MonoBehaviour
cuz i wanted to pass in a script
idk
well uhhh
- Why
- If so, why
MonoBehaviour
Memes arent allowed here, but really focus on restructuring this. You 100% do not need whatever that value type is.
If you wanna pass in a spawner script specifically then you dont use monobehaviour, use either some common interface or abstract class that the spawners all implement
First things first, get rid of that triple dictionary
i wanna call a method inside them and uhh... they are of type monobehaviour
either way starting a new coroutine is wrong approach
MonoBehaviour does not have a Spawn function. Why not pass in the type you actually want
if you want to pause each loop , the whole function needs to be IEnumerator and put yields in the loops
i didnt wanna pass in the type i actually want cuz i want to able to pass different type.. but ig then it wont know about the methods each type
nope not pause the loops
didn't you say you didn't want to spawn them all at once?
I suppose SpawnDelayer() could be returning a random value, causing each one to start at the same time, but delay for random lengths of time?
this is a bit diffuclt to explain cuz its like both a yes or no.
yes the loop tells all of the objects to spawn, but they wait a little before actually running the spawn method
if it makes sense
tbh Im lost at this point what op wants lol
yea
ye sorry it was a bit hard to articulate
Probably the best way to do this would be to have the spawners themselves spin up the coroutine that waits then spawns the object
So .spawn starts a coroutine with a random delay and then does whatever
yea but like due to how everything is set up, with .spawn being used in other scripts and havign a bunhc of different types pf spawners, id prefer if there was a way without changing the spawn method
So make a new method SpawnWithDelay that spins up a timer and then calls spawn
i suppose that is a solution, but if there is a way to do it via the original script and not the spawner script that would be nicer
The way to do that is the way you're currently doing it but pass in an object of the type you actually want instead of MonoBehaviour
meaning id need a method for each type of spawner, but.. is there a way to be able to avoid that and make a universal coroutine, or is that not possible?
No, you'd pass in whatever parent class or Interface defines that Spawn method
why is it red around this sprite?
but how would that look like? for example how would i be able to pass a spawner of type FireballSpawner in here
do you have transparency?
also not code related
You would make the function take whatever shared parent class or interface these all derive from
it was transparent on gimp when i drew it
ive looked for tutorials but i cant find any
did you set it as sprite in the texture import settings?
is it exported as a .png even?
jpg
then that would be the problem
okay lets try again
is there any shortcut way to correlate, say, "Color.green" to the string "Green", or do I have to make a dictionary or something?
you can just say "green" maybe i think? i dont remember fully
that or you can do a dictionary with Html hashvalues
ig depends on your usecase
I'll just make a dictionary