Author Topic: Do any of you code for your jobs?  (Read 8456 times)

0 Members and 1 Guest are viewing this topic.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #60 on: March 31, 2022, 04:42:47 AM »
Man, getting addicted to making sprites, sprite animations and music. Can stay up all night doing this. This is way more fun than the actual game making haha

My splash screen art is fucking terrible though. Cannot do art larger than like 16x16.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #61 on: March 31, 2022, 05:14:24 AM »


Like it's nothing special, but given that I have no artistic ability and I've been jumping into sprites & music entirely on my own and in a day I can pull off stuff like this pretty quick and no problem gives me some hope for cool stuff I can do in the future.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #62 on: March 31, 2022, 04:41:38 PM »
Also I fixed the respawn code in kind of a cheat shortcut way. I found where it tells it to respawn in the script and it says transform.position = respawn.position so I just changed it to transform.position = new Vector3(transform.position.x-1, transform.position.y-1, transform.position.z) and that fixed it so you just knock a bit to the side when you get killed and watch the explosion in the spot you were.

And yes, I've learned enough to know this code has a problem, because if you're at the lowest bounds of X or Y and you get hit you'd respawn 1 degree out of bounds. So if I was doing a public, good code, release I'd clean it up with some type of check if transform.x -1 is greater (or maybe less than since we're dealing with negatives) than x boundary && if tranform.y -1 is great than y, then do the code, else, respawn at transform.position.

Also I was trying to test the game over splash screen and realized at some point in all my script editing I broke the game and the player doesn't lose lives on death and it's impossible to game over. No idea how this happened but was able to debug fix it by finding the int variable for currentLives and that death is basically "on hit if currentLives > 0 respawn, else do game over" so I threw in another line at hit code that says currentLives -= 1 and it fixed it.

Nice being able to figure out quick fixes for stuff! Last weekend was rough trying to get my head around basic coding with a lot of wasted time not figuring things out. But starting to feel confident and able to do some basic code, art, music. So I think this weekend will be real productive since I just need time to actually make the game.

Nintex

  • The tide is turning
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #63 on: March 31, 2022, 04:49:06 PM »
Sounds like we can finally get "Dudebro III: The Ding Dong Slappening of GaaS" off the ground  :thinking
🤴

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #64 on: March 31, 2022, 07:22:08 PM »
Oh man, remember Dudebro. :lol

Tasty

  • Senior Member

Nintex

  • The tide is turning
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #66 on: March 31, 2022, 07:30:39 PM »


:salute

That's 13 years ago now.

I know exactly how the Rivet woman feels with her creation being taken away from her.
🤴

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #67 on: March 31, 2022, 07:31:59 PM »

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #68 on: March 31, 2022, 07:41:24 PM »
Sorry to highjack your thread Bebps. But...

https://en.wikipedia.org/wiki/Dudebro_II

Quote
Cuyahoga made up the title to mock another user who accused him of being a pedophile because he purchased and enjoyed the game Imagine: Babyz Fashion.

:doge

Quote
The game, originally scheduled for release in summer 2010

:lol

Quote
was later pushed to 2011

:rofl

Quote
The developers published for free level codes that allow users to download those [two custom Super Mario Maker] levels. They cautioned against spoiler culture when playing through these levels, as they might potentially ruin some crucial story beats from the yet-to-be-released Dudebro II.

:gurl

Quote
[In 2017] they announced plans to purge all references to NeoGAF, and start work under a new team on a spiritual successor. No further statements confirming the game is in active development were ever issued.

 :whatsthedeal

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #69 on: March 31, 2022, 10:05:51 PM »
My first level is the most terrible thing I've ever seen in my life but it's done. The biggest issue is holy cow there are hundreds of collision issues of going through everything even though there's no difference in the game object between an object you can't go through and one you can. Don't have time to deal with it for this project so will just file that under bugs. Also some enemies stick around after dying and you have to kill them twice even though all the enemies are just copy & paste prefabs, yet some are fine and some are fucked. Again, no time so this will just be a shit level and time to move on to level 2.

Now I'm trying to make a text intro to the level with a few dialogues popping up. I don't know how to do this yet in scenes so I'm making them as a series of splash screens one after another to then load into level 1.

I followed this guide which seems straight forward enough script to make each scene load and wait for a few seconds and then scenemanager loads the next scene.


But it's not working at all for me? No errors in the C# code or in the game but the scenes just sit and don't move to the next one.

here's my code:
Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Splash_Screens : MonoBehaviour
{

    public static int SceneNumber;
   
    void Start()
    {
        if (SceneNumber == 1)
        { StartCoroutine(ToSplashTwo());
        }
        if (SceneNumber == 2)
        { StartCoroutine(ToSplashThree());
        }
        if (SceneNumber == 3)
        { StartCoroutine(ToSplashFour());
        }
        if (SceneNumber == 4)
        {
            StartCoroutine(ToLevelOne());
        }
    }

    IEnumerator ToSplashTwo()
    {
        yield return new WaitForSeconds(3);
        SceneNumber = 2;
        SceneManager.LoadScene(2);
    }

    IEnumerator ToSplashThree()
    {
        yield return new WaitForSeconds(3);
        SceneNumber = 3;
        SceneManager.LoadScene(3);
    }

    IEnumerator ToSplashFour()
    {
        yield return new WaitForSeconds(3);
        SceneNumber = 4;
        SceneManager.LoadScene(4);
    }

    IEnumerator ToLevelOne()
    {
        yield return new WaitForSeconds(3);
        SceneNumber = 5;
        SceneManager.LoadScene(5);
    }
}

I created an empty game object in each splash screen and put the script in and saved for each splash screen.



Mainmenu is scene 0 in my build, so starting with scene = 1. I set the first splash screen to level 1, then scene #2 is level1 intro A, scene #3 level1 intro B, scene #3 level 1 IntroC, scene #4 is level 1 introD, and scene #5 is level1_game which is the actual gameplay level.

Sage, any idea why nothing is happening?



Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #70 on: March 31, 2022, 10:11:59 PM »
So I rewrote that script without the if statements to see if it would work if it just says "wait 3 seconds then load scene 2" and I stick it in an object in scene 1.

And it works. So something about the if statement is making it not work...

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #71 on: March 31, 2022, 10:13:17 PM »
Aha, I figured it out.

When I did int SceneNumber up top, by not giving it a value it starts at 0 and there's no if for 0. Need to set it as 1 in this case;

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #72 on: March 31, 2022, 10:39:21 PM »
Actually having something that sequentially works from main menu -> intro credits -> level that is winnable (or game over screen back to title) -> level 2 is a nice feeling even if the game itself is shit.

All about learning first and making it work even if it's held together by stitches. Cleaning up and improving starts from there!

Next up is learning how to write a level script that loads enemies at certain points for level 2. Then if I have time I'll try to make a level 3 that's just a single boss fight -> ending.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #73 on: April 01, 2022, 06:17:05 AM »
I've made so many songs and I dislike them all  :'(

Making music is not hard. Making good music that comes out the way it is in your head is hard. I used to play guitar so I have some sense of this but there I just play notes on guitar without thinking of where on the scale they are. Never was good at reading music. Trying to find the note I'm looking for here can be tough!

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #74 on: April 01, 2022, 09:59:19 AM »
Yeah, I would definitely suggest while you're still learning things you are very strict with your logic flow by - for example - always having an
Code: [Select]
else { Debug.log("I fucked up somewhere because this shouldn't run!"); }(or a more relevant error message) in every IF block to get into the habit of evaluating all code paths

Also, I can't say that's a bad tutorial, and if nothing else you can use it as an example of using coroutines as timers, but its a bit weird because Unity has had built in Splash Screens for uhhhh quite a few fucking editions now



But like I say, nothing wrong with knowing how to do scene transitions; I'd have probably made those coroutines actually check the levels loaded before moving on rather than fixed wait times, but like I say thats useful info to know how to do anyway

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #75 on: April 01, 2022, 01:17:49 PM »
I've made so many songs and I dislike them all  :'(

Making music is not hard. Making good music that comes out the way it is in your head is hard. I used to play guitar so I have some sense of this but there I just play notes on guitar without thinking of where on the scale they are. Never was good at reading music. Trying to find the note I'm looking for here can be tough!

keep an eye out for humble bundles that give packs of pre-made assets for developers, I know that feels like cheating but I mean, that's what those resources are for, some guy made a bunch of music loops and said "I hope somebody who needs them can use them"

or just buy some now if you find ones you like

https://www.bitbybitsound.com/royalty-free-music/

you probably already own this guy's music if you bought any of the giant bundles during recent humanitarian causes:

https://itch.io/b/520/bundle-for-racial-justice-and-equality

https://itch.io/b/902/indie-bundle-for-palestinian-aid

https://itch.io/b/1316/bundle-for-ukraine
« Last Edit: April 01, 2022, 01:22:00 PM by Uncle »
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #76 on: April 01, 2022, 03:49:06 PM »
Yeah, I would definitely suggest while you're still learning things you are very strict with your logic flow by - for example - always having an
Code: [Select]
else { Debug.log("I fucked up somewhere because this shouldn't run!"); }(or a more relevant error message) in every IF block to get into the habit of evaluating all code paths

Great point. Will try to do that in the future.

Quote
Also, I can't say that's a bad tutorial, and if nothing else you can use it as an example of using coroutines as timers, but its a bit weird because Unity has had built in Splash Screens for uhhhh quite a few fucking editions now

(Image removed from quote.)

But like I say, nothing wrong with knowing how to do scene transitions;

Yeah, I have no idea all the features already in Unity. There are a lot of things and still learning. That said since I don't know/have photoshop or any image editor that can even do layers outside this sprite editor, so building my text screens as scenes was actually kind of helpful and like you said learning how to scene change is really important for making anything.

Quote
I'd have probably made those coroutines actually check the levels loaded before moving on rather than fixed wait times, but like I say thats useful info to know how to do anyway

Tbh at this point I don't know the difference between a coroutine and a method.

If the code said:

Code: [Select]
If {posting on Bore, doPost(); Else debugLog"why aren't you posting on Bore;}"

void doPost(){
Type up blah blah blah;}

How is that different than

Code: [Select]
If {posting on Bore, StartCoRoutine(doPost()); Else debugLog "why aren't you posting on Bore;}

IEnumerator doPost {
Type up blah blah balh;}

I don't think I ever did CoRoutines in my C++ class and my Unity class hasn't covered CoRoutines yet so I know nothing about them but they just seem like methods but people prefer using them?


Also in your post you say you'd have it check the levels, what does that mean?


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #77 on: April 02, 2022, 12:37:31 AM »
So I want to add a "Lives: 0" display in the UI to show the current lives outside of the debug screen.

The int with currentLives is in the health.cs script attached to the player.

The UI Display is in a separate script and using the class UIElements to override updateUI to display a text string. I can't get this to work under the health.cs script since it won't let me have the script be a child of MonoBehaviour and UIElement.

The simple thing would be to figure out how to grab that int currentLives that is on the Player in the Health.cs script from my Display script. But this is a bit beyond me and goes back to trying to get separate scripts to interact. I can find the gameObject that is player with Find.gameObject.Player, right? So how do I go from there to getting the variable from a script that's attached to it?

Transhuman

  • youtu.be/KCVCmGPgJS0
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #78 on: April 02, 2022, 02:29:46 AM »
I always wanted to make a game that took elements from top-down zelda GBA games like Link's Awakening, Oracle of Age, etc, and I started watching tutorials and shit, but that shit is hard. If I had to do my life over again i'd definitely learn 2 code though. I remember in highschool I managed to make a little Zelda movement simulator in flash (walking around, bunping against walls, being carried by water) but I can't even imagine being able to learn how to do that now.
« Last Edit: April 02, 2022, 02:34:54 AM by Transhuman »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #79 on: April 02, 2022, 03:52:48 AM »
Been coding after work for like 6-7 hours straight last few nights. Just got stage 2 done, outro to stage 3 (minus an animation I want to put in) and ending story bit done.

Feels good have 2 full micro-stages complete. Still a shit game, but great learning experience. Gonna try to do a stage 3 tomorrow and then add a bunch of tweaks and then it'll all polishing clean up to make it slightly less shit before I turn it in.

It's good Unity doesn't have like gameplay time log. I'm probably gonna be somewhere between 50-100 hours on this first real project over like 10 days.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #80 on: April 02, 2022, 03:59:04 AM »
I always wanted to make a game that took elements from top-down zelda GBA games like Link's Awakening, Oracle of Age, etc, and I started watching tutorials and shit, but that shit is hard. If I had to do my life over again i'd definitely learn 2 code though. I remember in highschool I managed to make a little Zelda movement simulator in flash (walking around, bunping against walls, being carried by water) but I can't even imagine being able to learn how to do that now.

I keep reading these books/articles over the last year or two of all these famous artists and people who didn't publish their first book/movie/album or whatever until their 40s and it gives me hope that I can still maybe get into game making even as an old dude. Never too late!

When I was a kid I was really into coding and game making stuff. I remember making like king kong on a tower you have to climb game in QBasic and a jumpman clone. The one area I was legit credible was I used to design levels for Doom II/Quake/Duke 3d/Unreal 99 and I used to actually be pretty good at it. I made one breakout Doom II level that actually got played a bit online at the time called Rooftops where it's a bunch of skyskraper rooftops and you jump from building to building including going through the interior of buildings and there are warp points all around to reset you back up to spots higher up since as you keep going from building you generally are moving downwards. Was a good fucking level and I was like 12 or something. Wish I still had my old floppy disks somewhere. Was definitely considering trying to be a level designer. Just ended up going in a different direction.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #81 on: April 02, 2022, 03:13:22 PM »
Sage, any chance you're available for a bit today to help me on some stuff? There's just a link of code that I don't know yet which is blocking off a ton of possibilities by having things interact with each other and I need help figuring that out if I want to do more interesting things with my game.


Like I'm trying to have a 3d polygon object attack the player in this 2d game. The problem being the physics colliding interaction between a 3d object and 2d object. Initially my bullets passed right through the 3d object even with the 3d collider on. I googled it and the get around I found was you make a hidden 2d object within the 3d object (as a child gameobject) and throw on the 2d rigid body & collider.

Doing that makes my 3d object appear solid and bumping into it kills you and bullets stop at it because they collide with the hidden 2d object underneath.

But I want to be able to destroy the 3d object with my bullets and putting a health script on the 2d object just kills the hidden 2d object and putting the health script (which includes take damage/check death) on the 3d object does nothing since it is not interacting with anything.

I feel like it should be possible to write a script that says "If my child gameobject becomes setActive(false), then destroy.this" and have the health script on the child game object set active to false when shot.

But the missing link again is my ability to figure out how to get two separate scripts & objects to interact. I have no idea how to write a script you put on a gameobject that looks to its child each update to see if it's been set active(false)? I would assume the code would be

Code: [Select]
blah blah Update()
{
   check child();
]

void check child();
{ if GameObject.Child = SetActive(true)
{debugLog("Still Alive");
Else
{Destroy(gameObject);}

I just don't know for that "GameObject.Child" spot what I write to have it look into the child attached?

I think it has something to do with this. Just need to figure out how to name things and code them.
https://docs.unity3d.com/ScriptReference/Transform.GetChild.html

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #82 on: April 02, 2022, 03:29:57 PM »
Going to see if this code works?

 void Update()
    {
      if (gameObject.transform.GetChild(0).gameObject.SetActive(false);)
        { Destroy(gameObject); }
    }

*edit* doesn't work, says can't convert a true/false bool to a void.

I also tried having update say checkinnerbody();

and make a non-void checkinnerbody() method that did that check but it is giving me the same error.
« Last Edit: April 02, 2022, 03:37:43 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #83 on: April 02, 2022, 04:05:34 PM »
Got it checking now but still running into some issue. Trying to figure it out.

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlanCheck2d : MonoBehaviour
{
    void Update()
    {
        checkInnerody();
    }

    private void checkInnerody() {
        Debug.Log("test" + transform.GetChild(0).gameObject.activeSelf);
        if (transform.GetChild(0).gameObject.activeSelf == (false))
        {
            Destroy(gameObject);
        }
        else
        {
            // do whatever you want if child is inactive

        }
    }

}

It's disappearing on collision with player, but not with bullets and not sure why but debugging it now.

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #84 on: April 02, 2022, 04:10:57 PM »
I always wanted to make a game that took elements from top-down zelda GBA games like Link's Awakening, Oracle of Age, etc, and I started watching tutorials and shit, but that shit is hard. If I had to do my life over again i'd definitely learn 2 code though. I remember in highschool I managed to make a little Zelda movement simulator in flash (walking around, bunping against walls, being carried by water) but I can't even imagine being able to learn how to do that now.

I remember captivating (well, holding) my freshman high school CS class' attention for like 5 minutes at the end of the year with... my single-screen, non-scrolling recreation of Super Mario Bros. 1 in Visual Basic 6. Had basic movement but not jump physics (pressing "up" moved Mario up). The teacher rolled her eyes a little. Everyone else went back to playing Unreal Tourney behind her back.

Simpler times...

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #85 on: April 02, 2022, 04:45:25 PM »
I give up on this effect. This was supposed to be a productive day and I've spent the last 3 hours just trying to get one effect that doesn't even matter in the stage to work and I have no idea why it doesn't. I enjoy the game making but this is the stuff that burns me when I waste so many hours trying to get one little thing to work and cannot do it for the life of me and cannot understand why.

Basically I can get my child 2d sphere to setfalse on ship hitting collision before destroying and that setfalse destroys the 3d parent. COOL.

But I cannot get this to work with bullets and damage and health. I can get the child to take damage from bullets and die but it always just destroys and then the parent breaks the game with error that child is out of bounds. I put a million "gameObject.SetActive(false);" every fucking where in the script trying to get the child to set false before dying after taking damage from bullets but nope, nothing is working.

I can't even get the child to not destroy. There is no where in the code telling it to destroy... it's something hidden within this code I'm using that is making this impossible.

I need to take a break and get lunch and then do something else. Man, when you're making progress it's exciting and encouraging and you just want to keep creating and when you're stuck against a wall it just makes everything shit.  :'(

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #86 on: April 02, 2022, 04:50:21 PM »
Nevermind, I put some debuglogs in and fixed it. Though this may break a lot elsewhere...

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #87 on: April 02, 2022, 05:10:59 PM »
So yeah, by changing how health script works stage 2 broke. I got around it in stage 3 by not destroying the objects and just setting them false (bad I know, but for a small amount of objects should be fine)


So now on stage 2 the enemies keep firing bullets after they are dead because they are false and not destroyed.


Is there a simple way to use different health scripts between levels?

Like level 2 uses the original health script, level 3 uses my modified one called health_two.cs? Because I swear when I tried that it broke everything because everything else in the game is setup to look for health.cs.

If only I could make the levels act like completely separate games using unique scripts and transition between them.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #88 on: April 02, 2022, 05:19:49 PM »
Yeah, I literally have 2 scripts on the same gameobject called Health and Health_1, both are 100% the same code. This is the only script on the game object. When I enable Health.cs the object dies after x amount of bullet shots. When I enable Health_1.cs the object doesn't take damage or die. This is so bizarre.

It has to be something in the gamemanager that is referencing health?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #89 on: April 02, 2022, 05:36:12 PM »
Uhhhh, I fixed the entire problem and I don't know why it works, but ok?  :doge

The health code has teamIds built in.

So originally the code section that killed things when shot read:

Code: [Select]
Destroy(this.gameObject);

Which I modified to
Code: [Select]
Debug.Log("GettingHere2");
gameObject.SetActive(false);

To fix my issue of parent getting out of bounds errors because child was destroyed before it could read the child as inactive. This did not work:
Code: [Select]
Debug.Log("GettingHere2");
gameObject.SetActive(false);
Destroy(this.gameObject);

I'm guessing because it's too fast and still destroyed the object because update could be called with the parent to check if the child was active.

 
So anyhow, I tried using this for teams:

Code: [Select]
Debug.Log("GettingHere2");
gameObject.SetActive(false);
       
        if (teamId == 1)
        { Destroy(this.gameObject); }
        else
        { Debug.Log("Team ID: " + teamId); }

Thinking I could have the normal enemies in stage 1/2 be team 1 and be destroyed
While my special enemies in stage 3 could be a team 2 and not destroyed and just set false instead.

This did fix my enemies in stage 1/2 and destroys them, yay.

And if I set my special enemies in stage 3 to team 1 I get the out of bounds error like before

but if I set my special enemies to Team 2, they setactive(false), the parent sees that and destroys itself AND the child destroys itself instead of just being set inactive (which was originally happening using my set false code).

So the end result is perfect, but I have no idea why team 2 is still destroying itself but just a little slower so there's time for the parent to check active/inactive state of the child??

Anyhow, now that everything is working again, time for lunch and then actually designing stuff for the rest of the day since I got the code I wanted to do the stage effects I want.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #90 on: April 02, 2022, 05:36:29 PM »
Tbh at this point I don't know the difference between a coroutine and a method.

Also in your post you say you'd have it check the levels, what does that mean?

Coroutines don't run on the main thread, so they run 'when they can' (which is pretty much instant on modern multithreaded cpus) but in terms of flow control are pretty useful as they don't stop until their condition is met; so you've probably seen them mostly being used as mini-timers, with something like
Code: [Select]
[ienumerator,thing]
dostuff;
yield return new wait for seconds 5;
do some more stuff;
end code block

but you can make the yield condition pretty much anything you want; they're pretty useful.

For the level stuff, you can check level load progress, and instead of doing fixed time waits could do it as like, level loaded 20% this, level loaded 40% that, etc is what I meant.

Oh yeah if you need free photoshop: check out www.photopea.com its basically web based photoshop

So I want to add a "Lives: 0" display in the UI to show the current lives outside of the debug screen.

The int with currentLives is in the health.cs script attached to the player.

The UI Display is in a separate script and using the class UIElements to override updateUI to display a text string. I can't get this to work under the health.cs script since it won't let me have the script be a child of MonoBehaviour and UIElement.

The simple thing would be to figure out how to grab that int currentLives that is on the Player in the Health.cs script from my Display script. But this is a bit beyond me and goes back to trying to get separate scripts to interact. I can find the gameObject that is player with Find.gameObject.Player, right? So how do I go from there to getting the variable from a script that's attached to it?

Not sure I'm following this, and it might just be using different terms, so lemme try and break this down with how I'd do it at beginner level;

So first off, when you say 'child', in Unity, a child object is like, attached to a 'parent' object, and its like a physical relationship in the heirachy; they're like folders and subfolders in windows explorer.

in code, when you do myclass : monobehaviour, youre not making it a child of monobehaviour, you're using whats called inheritance to get default code that you can overwrite - so like, all the builtin methods like update() onstart() oncollision() etc are all premade monobehaviour methods.
If you really want to inherit from multiple classes, you actually can't, but you kinda sorta can by using whats called an interface, but tbh I think this is a running before you can walk type of thing you don't need to do just to do UI stuff, so lemme show you an alternative and I'll cover interfaces if you do really need it?

You're best off - to start with - thinking about unity almost like plumbing; you set up the variables you're gonna want in script, but you then manually connect up the object refernce onto your script by literally dragging and dropping it, rather than doing finds for everything.

So if you have a UI Text component onscreen, you can make this script;

Code: [Select]
using Unity.UI; (this lets you acces the UI.Text directly)
class UI_Timer : Monobehaviour
{
     public Text uiTextElement;
     int timerValue=0;

     Update()
     {
          uiTextElement.Text = "Timer: "+ timerValue;
          timerValue++;
     }
}

and drag and drop your Text Gameobject onto the Text variable space, and when you run it you'll have a running timer in that text field

Does that make sense? For updating UI information, as its onscreen all the time anyway, you dont actually need to 'search' for it, you can just point directly to the gameobject - this really is the easiest way of doing this stuff at this stage and for low complexity games

Sage, any chance you're available for a bit today to help me on some stuff? There's just a link of code that I don't know yet which is blocking off a ton of possibilities by having things interact with each other and I need help figuring that out if I want to do more interesting things with my game.


Like I'm trying to have a 3d polygon object attack the player in this 2d game. The problem being the physics colliding interaction between a 3d object and 2d object. Initially my bullets passed right through the 3d object even with the 3d collider on. I googled it and the get around I found was you make a hidden 2d object within the 3d object (as a child gameobject) and throw on the 2d rigid body & collider.

I've been drinking, so lemme get back to this tomorrow, but just make sure you're seperating 'FORM' and 'FUNCTION'; if you wanna combine 2D objects and 3D objects, that don't mean shit if its only the visuals you're talking about, but you're gonna fuck stuff up if you start trying to use both Collider and Collider2D and Rigidbody and Rigidbody2D in the same script (or at the very least gonna make stuff way more complicated than it needs to be

So let's break this down to basics again; (also I don't think you need to care about child shit - if you destroy the parent object, the child goes with it)

So make a 3D Cube game object in the hierachy, then right click it and make a Sprite (or a Quad if your image is a texture not a Sprite).
When you right clicked it, you made it a Child of the based 3D cube.

Turn off / remove the mesh renderer on your cube, and you have an invisible 3D box as your parent.
If you put your movement script on that invisible box (and a Rigidbody), all your collisions and code will affect that invisible 3D cube, but from the players perspective, all they see is the 2D child object (because the 3D cube is invisible).

My best guess why your stuff isn't working with your 3D object, is because the script is called Rigidbody2D and Oncolision2D events rather than Rigidbody and Oncollision events?
Because the '2D' system in Unity is basically an entirely seperate physics engine bolted onto the existing one - IIRC, Unity uses Havoc for its 3D physics and Box2D for its 2D, so although they share a lot of similar commands in the API for interoperability reasons (and so its easy for coders to move from pseudo2D to actual 2D code) the two systems won't actually interact

Madrun Badrun

  • twin-anused mascot
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #91 on: April 02, 2022, 05:39:21 PM »
I really like your excitement about this Bebpo. 
NtGay

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #92 on: April 02, 2022, 05:43:40 PM »
Sage, I'll parse that when I get back from lunch.

One thing I want to do conceptually but I'm ok turning this project in without it because it might be too advanced for me.

I want the hud to say one thing in the top-corner like

"SCORE" (which it currently does)

and then mid-boss fight after a certain point (phase transition)

I want that SCORE UI text to fall off the screen (put a move script on it?)

And then be replaced by a new phrase that is like

"EROCS" 

Not sure how to do that in terms of transitioning. I'm guessing if I can figure out how to work with timers or other object interactions I can say after health reaches 50, run the score movement drop script and then spawn EROCS text which would just be a duplicate of the score text with different text in the field).

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #93 on: April 02, 2022, 06:32:07 PM »
Not sure how to do that in terms of transitioning. I'm guessing if I can figure out how to work with timers or other object interactions I can say after health reaches 50, run the score movement drop script and then spawn EROCS text which would just be a duplicate of the score text with different text in the field).

Yeah, pretty much exactly like that - its like ragdolling something; hide the 'real' thing, then drop in a dummy copy of it at that position and let it drop.

It's a bit more complicated if you're not using a diegetic UI (which most aren't) because of stuff like, fonts rendering at different point sizes at different resolutions and shit, but, yeah

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #94 on: April 02, 2022, 07:13:53 PM »
Ok, back, Sage, I read your post and yeah I meant inheritance about classes.

That makes a ton of sense with IEnumerators and timers. I may use that right now for changing stuff during this boss fight since timers would help. Right now I'm thinking of just doing asynchronous scene transitions for each boss phase, so like when the boss "dies" you can't tell its died because it visually persists but the death of the boss at like 50% HP causes the next stage part to load and now the UI canvas can say "EROCS" instead of Score and the boss can be using a new moveset because it's an all new stage.

The thing with lives is the script I'm using has an int called "currentLives" in Health which is where the current # of player lives are stored. I put that on my player and in the debug window can have it update each time I lose a life and give me the current amount of player lives available.

It sounds like the easiest solution maybe within the same health script to create a public text element that = currentLives at any point?
Actually scratch that, that would make the text appear on the player ship since it's not its own object.

Still not sure how an object in the Canvas UI would be able to access that currentLives counter, but ehhh I can save this for later.


The collider situation was actually the opposite. I had 3d colliders in the 3d object which did nothing and 2d colliders in the 2d object which did the collision with the bullets and then I tied the lifetime of the 3d object to the life of the 2d hidden object so when that object which is having physic collisions with the 2d bullets dies the 3d object goes with it.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #95 on: April 02, 2022, 07:16:37 PM »
One problem I have btw is that every enemy & the player uses the same enemy & health scripts which define a few things like HP and physics interactions and damage. So I can make changes to just effect one enemy without it fucking them all up. Though maybe this TeamId thing will help that.

Otherwise if the boss had a boss specific script I could say "when HP = 50% -> sceneload (20)" or whatever to move to phase 2.


A lot of my issues would be solved if I had written the enemy & player scripting from bottom up. Will do that next project.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #96 on: April 02, 2022, 07:24:03 PM »
I'm trying to use that Timer code you posted to display a timer text and I'm getting an error:

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    public Text uiTextElement;
    int timerValue = 0;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
   
    uiTextElement.[b]Text[/b] = "Timer: " + timerValue;
    timerValue++;
       
    }

}

The bold is giving me this error:

'Text' does not contain a definition for 'Text' and no accessible extension method 'Text' accepting a first argument of type 'Text' could be found (are you missing a using directive or an assembly reference?)   


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #97 on: April 02, 2022, 08:44:36 PM »
Also one thing that would be real helpful is, is there a trick to using different versions of the same scripts in different scenes?


Like I want to change where my respawn respawns for stage 3 only and the respawn script effects all scenes. So I'm not sure how to make it only change respawn on stage 3. Like for stage 3 instead of respawning at -1/-1 from death position I want to respawn at death position just for that stage because you're not supposed to be moving at all in that stage.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #98 on: April 02, 2022, 09:54:49 PM »
Ok, I've got a 3 phase final boss as 3 separate scenes. I just need to figure out how to write a script to change from one to another during the fight using the scene loader.

remy

  • The abominable Hoeman
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #99 on: April 02, 2022, 10:26:45 PM »
I'd have a variable that keeps track of the phase and then use a switch to change stuff based on which phase it is. Dunno if that's dumb tho

remy

  • The abominable Hoeman
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #100 on: April 02, 2022, 10:30:16 PM »
I'm trying to use that Timer code you posted to display a timer text and I'm getting an error:

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    public Text uiTextElement;
    int timerValue = 0;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
   
    uiTextElement.[b]Text[/b] = "Timer: " + timerValue;
    timerValue++;
       
    }

}

The bold is giving me this error:

'Text' does not contain a definition for 'Text' and no accessible extension method 'Text' accepting a first argument of type 'Text' could be found (are you missing a using directive or an assembly reference?)   
Lowercase T https://docs.unity3d.com/2018.3/Documentation/ScriptReference/Experimental.UIElements.TextElement.html ie uiTextElement.text

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #101 on: April 03, 2022, 12:04:11 AM »
I'd have a variable that keeps track of the phase and then use a switch to change stuff based on which phase it is. Dunno if that's dumb tho

I'm dumb and have been coding for like almost 20 hours straight. Can you post some example code? Brain is pretty gone.


I've just been cleaning up the game for the last few hours since I'm kind of stuck on some code bits. I now have everything up until stage 3 pretty smooth including loading stage 3 part 1. I just need to figure out how to combine these 3 phase scenes and outro to the ending. Then I gotta make a few more sprites and a few more songs and I'm done.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #102 on: April 03, 2022, 12:09:06 AM »
I'm trying to use that Timer code you posted to display a timer text and I'm getting an error:

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    public Text uiTextElement;
    int timerValue = 0;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
   
    uiTextElement.[b]Text[/b] = "Timer: " + timerValue;
    timerValue++;
       
    }

}

The bold is giving me this error:

'Text' does not contain a definition for 'Text' and no accessible extension method 'Text' accepting a first argument of type 'Text' could be found (are you missing a using directive or an assembly reference?)   
Lowercase T https://docs.unity3d.com/2018.3/Documentation/ScriptReference/Experimental.UIElements.TextElement.html ie uiTextElement.text

Thanks, it compiles now but I stick it on a gameobject either in the UI canvas or not and it's not doing anything?

Shouldn't a timer: 0 show up and start counting upwards?


I want to put dialogues into this boss fight and if I can figure out how to make text appear and change during the fight I should be able to do it.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #103 on: April 03, 2022, 12:11:05 AM »
Gonna watch this and see if it answer that:



*edit* nm, that wasn't it. Was just showing permanent text on the main camera. I'm looking for like being able to make text a game object I can drop somewhere in the scene and have activate on a timer.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #104 on: April 03, 2022, 12:27:22 AM »
Ok, figured out that attaching a canvas to a bank 2d sprite with 0% opacity and then textmeshpro to that canvas gets the text to show up.
Now I just need to figure out how to make the text disappear and appear at certain times so I can change the dialogues. Actually I put a timed object destroyer script on it and that makes it go away.

Now I just need to figure out how to time it to appear?

Also got that timer code working. I wonder if I can use that timer as a way to trigger things through scripts since I can see what time it is when I want things to appear.
« Last Edit: April 03, 2022, 12:33:46 AM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #105 on: April 03, 2022, 12:50:52 AM »
Gonna try this conceptually, making text objects with a script that sets them to active(false) at awake. Then this timer script should set them active at a certain time?

Code: [Select]
public class Timer2 : MonoBehaviour
{

    public Text uiTextElement;
    int timerValue = 0;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        uiTextElement.text = "Insanity: " + timerValue;
        timerValue++;
        if (timerValue == 1000)
        { displayText(); }

    }

    public void displayText()
    { transform.GetChild(0).gameObject.SetActive(true); }
}

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #106 on: April 03, 2022, 12:54:42 AM »
Oh shit, it works!

I can now have things inactive that will active based on this timer code. Thanks Sage and remy, this will go a long way towards getting this done. I can even scene load at certain time points to change between phases. Conceptually this should finish the last of the coding I need to complete this game and I can just focus on art/music and polish.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #107 on: April 03, 2022, 01:23:02 AM »
Yeah, that was it. The missing link that's the game changer. Got text stuff going, my scene changes are working. Now that I have a timer I can do lots of stuff. Since the text childs destroy themselves after a few seconds the next one is always child(0), so the code was pretty easy!

Code: [Select]

        uiTextElement.text = "Insanity: " + timerValue;
        timerValue++;
        if (timerValue == 600)
        { displayText1(); }
        if (timerValue == 1000)
        { displayText1(); }
        if (timerValue == 1800)
        { displayText1(); }
        if (timerValue == 3100)
        { displayText1(); }
        if (timerValue == 6600)
        { displayText1(); }
        if (timerValue == 7900)
        { displayText1(); }
        if (timerValue == 8300)
        { SceneManager.LoadScene(17); }
    }

    public void displayText1()
    { transform.GetChild(0).gameObject.SetActive(true); }

About the only thing I still don't know how to do is display ship lives :|  Not a big deal, though players probably want to know how many lives they have left.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #108 on: April 03, 2022, 02:47:16 AM »
Actually, had one more final piece of code to figure out. Phase 2 of my boss fight requires you to kill the 2 parts of the boss to then load to phase 3.

Spent the last 45 mins trying to figure out how to get count of enemies on screen through the timer script (or a new script) so I could tell it to change scenes after the 2 enemies were killed.

After 45 mins, my end barely working result was going to the game manager and putting in:

public void IncrementEnemiesDefeated()
    {
        enemiesDefeated++;
       if (enemiesDefeated == 2 && SceneManager.GetActiveScene().name == "Level3_Game - Second Phase")
        { SceneManager.LoadSceneAsync(18); }


      if (enemiesDefeated >= enemiesToDefeat && gameIsWinnable)
        {
                LevelCleared();
            }

Bolded being what I put in which is extremely specific and can only be used on a case by case basis of putting in the scene name and the enemy count in game manager.

The problem is that their "levelcleared(); code pops up a victory splash screen with a "proceed to next level" button after all enemies are defeated. Which doesn't work when you want a seamless transition from one phase to another during a boss which is why I had to mickey mouse the whole thing. Sigh.

I need to make this transition work better but otherwise if I do this one more time to transition after the final boss final phase is killed to the ending that should be it for code for this project and it's just assets left for tomorrow.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #109 on: April 03, 2022, 04:46:25 AM »
Phew, finished ALL the coding for the game at like 12:49pm after coding all day from like 10am and doing very little asset work. I ran the game from start to finish and...I hit a weird game killing bug in stage 3 that only occurs if you've played four mins of stage 2 prior.

Took me so.long to debug, but I got it. Also fixed another bug with my splash screens after game overs or level select mixing up.

Finished it from start to finish. It's a complete game. Lasts about 5-7 mins. First game I've finished making since I was like 15 years old.


Now I'm still missing a bunch of assets and the project is due tomorrow night so gonna be hustling to get the rest of the art/music/sound effects/text/polish in, but creating that stuff is more fun than all these hours trying to figure out how to get stuff working and banging the head against the wall. So should be a good day provided I can get some sleep now lol. Didn't even get dinner tonight  :'(

remy

  • The abominable Hoeman
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #110 on: April 03, 2022, 05:40:55 AM »
About the only thing I still don't know how to do is display ship lives :|  Not a big deal, though players probably want to know how many lives they have left.
You have your lives stored as a variable somewhere right? And in your UI code you're displaying the value of the timer.

Lives are probably conceptually the same as the time. You just need to point your UI code to where you're storing the lives.

Awesome to hear you got it done though. I wanna play it.

This thread has also made me want to get back into making stuff as a hobby again lol. Maybe after I finish endwalker I'll do the course you're doing  :P

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #111 on: April 03, 2022, 08:16:33 AM »
Also one thing that would be real helpful is, is there a trick to using different versions of the same scripts in different scenes?

If you feel like it when you're done, I'd really like you to rewrite this from the scratch but without the stuff thats already there, because I can't help but feel you're getting misled on some stuff or not quite getting the rationale behind why theyre doing what they're doing, because if you're breaking scripts up into effectively components that do things, you should be able to use basically the exact same script in hundreds of different places; like, a movement script can be used by players or enemies, its just getting its inputs from either the player or an AI controller, a health system is a health system, a damage system is a damage system etc.

Yeah, that was it. The missing link that's the game changer. Got text stuff going, my scene changes are working. Now that I have a timer I can do lots of stuff. Since the text childs destroy themselves after a few seconds the next one is always child(0), so the code was pretty easy!

...

About the only thing I still don't know how to do is display ship lives :|  Not a big deal, though players probably want to know how many lives they have left.

Like this is an example where I'm not sure you're getting it, but you're getting results you want so you're good...?
Because I was trying to show you how to connect up a UI element, and then update it via code, rather than write you a good timer, lol. That timer - although yeah it works! - is kinda awful, because its gonna hammer your UI at 400fps or whatever uncapped framerate is, lol.

So if you wanna show lives, you can just do this:

Code: [Select]
public Text livesTextUI;

void UpdateLivesUI(int lives) // call this method whenever you change the lives value, and send it your updated lives variable
{
     livesTextUI.text = "Lives Remaining: " + lives; // or however you want to phrase this; eg could be livesTextUI.text = lives + " / " + maximumLives;
}
dragging and dropping your lives UI text component into the variable field

For a more robust / readable Timer codesnippet, you could do something like;

Code: [Select]
float timerCurrent=0f; // timer value
bool runTimer=false; // for a simple start / stop toggle
public Text timerTextUI;

void StartTimer(float tickrate)
{
     runtimer=true;
     InvokeRepeating("MyTimer", 0, tickrate);
}

void MyTimer()
{
     if (!runtimer) { StopTimer(); return; }
     timercurrent++;
     timerTextUI.text = timercurrent;
}

void StopTimer()
{
     runtimer=false;
     CancelInvoke();
}

void RestartMyTimer(float tickrate)
{
     timercurrent=0;
     StartTimer(float tickrate);
}


which would take an input in seconds, and then run every tickrate seconds (and its a float, so you could do 0.5 if you wanted 2x per second or whatever)


Lives are probably conceptually the same as the time. You just need to point your UI code to where you're storing the lives.

yeah, exactly - the Text variable is just a UI Text string - you can make it say anything you want

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #112 on: April 03, 2022, 01:17:13 PM »
Couple of things from your post.

1. Yeah, re-writing the code to be all my code and more efficient and better understand stuff would be good. I'll try to do that while I'm taking my next class on 2d platformers before I get to the actual "write a 2d platformer" game part. That way I'll have time and will be good practice.

2. Multiple scripts, I do get that if you're efficient you can do things in one script which is mostly how my project is setup. Like you just need to put in public bool various checkboxes to modify that script to work in many different ways. A good example would be a gamemanger script that figures out how to end the level. You could have a checkbox that says "end level when enemies killed?" "enemies that need to be killed __", and "end level when specific enemy killed?" "enter name of specific enemy that will trigger this _______", "end level after X amount of time?" "enter what time the level will end ____", "do you want to go to a win screen when level ends Y/N (if not will instantly transition to next scene)" "do you want to wait before loading next level?" "if so how long to wait ____" etc... something like that would be very flexible.

One spot I need multiple scripts is for my story scenes because there is no good way to grab the currentscene number as an int? I googled and people had complex array division ideas for that, but built into scenemanager is only a way to get the currentscene name. So the problem with my splash screen scripts for my story between levels is to start the story chain of scene changes it needs to have an int that increases per scene. If you use that same script for different story sequences the int will get all messed up. So I ended up using a different version of the script for each story sequence and the first thing the script does is set an int that increases. Probably easier to explain with code than words though.

3. For showing lives. I understand how to show UI elements thanks to that timer script your wrote. The reason I said I don't know how to show lives is what "lives" are is a formula that depends on other scripts because it gets adjusted as you take damage and die. So currentLives is an int stuck within the health.cs script. I'd like to write a fresh script called "Showinglives.cs" that somehow was able to grab that currentLives variable from the health.cs script and show it to the UI but I don't know how to do that (how to grab that int currentLives from the health script in my showlives script). I can get around it though by putting the show UI lives code within the health.cs code where that variable is, so that's what I'll do.

When this is done, the next thing I want to do is read/watch some long detailed classes on how to get different scripts to talk to each other and to practice that a ton until I'm comfortable. Because it is one of the major things I still don't know how to do. Like in my game the gamemanager script freely calls methods that are in other scripts that if I tried doing that in my own script the game would balk saying that method doesn't exist in my script I wrote. Other scripts then send things to the game manager and back and forth. It seems the game manager can do that, but to do that with other scripts it's more complicated. If I want to write a fresh script that says "yo, give me the current values of variables in 5 different scripts running on this object right now" I don't know how to make that work?

4. Oh shit that is bad on the timer being cpu dependent because I have a combination of move speed objects mixed with timers and if the time is different for every computer that will completely break level 3. I guess first thing I'm doing this morning is re-writing my timer with delta.time instead and re-timing everything in stage 3.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #113 on: April 03, 2022, 01:37:59 PM »
One spot I need multiple scripts is for my story scenes because there is no good way to grab the currentscene number as an int?

Nah, thats definitely not right...
Code: [Select]
SceneManager.LoadScene(int)specifically takes an int - I've literally never used a string for that stuff; you can get current scene with Scene.buildIndex by doing something like
Code: [Select]
int GetScene()
{
     scene = SceneManager.GetActiveScene();
     return(scene.buildIndex);
}

When this is done, the next thing I want to do is read/watch some long detailed classes on how to get different scripts to talk to each other and to practice that a ton until I'm comfortable. Because it is one of the major things I still don't know how to do. Like in my game the gamemanager script freely calls methods that are in other scripts that if I tried doing that in my own script the game would balk saying that method doesn't exist in my script I wrote. Other scripts then send things to the game manager and back and forth. It seems the game manager can do that, but to do that with other scripts it's more complicated. If I want to write a fresh script that says "yo, give me the current values of variables in 5 different scripts running on this object right now" I don't know how to make that work?

So without getting into stuff like observer patterns or delegates / subscribers, you can access public methods from other scripts if you have access to that other script.

So before we did that with colliders, as when things collide they can talk to each other?
If a thing you collide with has a Health.cs script on it, and in that script it has a public TakeDamage(int damage) method in the health script, you can do

Code: [Select]
OnCollisionEnter (Collider col)
{
     int damage=10;
     Health variableRepresentingAScriptCalledHealth = col.getcomponent<Health>();
     variableRepresentingAScriptCalledHealth.TakeDamage(damage);
}

If the scripts are on the same object, you can find them the same way, by checking the components the object this script is attached to (and might wanna have an 'if not null' check for safety).
You can also setup explicit references in the Unity inspector, as a Player script is likley to have a bunch of references setup for shit most players have, like movement, audio, UI elements etc

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #114 on: April 03, 2022, 01:59:40 PM »
Nah, thats definitely not right...
Code: [Select]
SceneManager.LoadScene(int)specifically takes an int - I've literally never used a string for that stuff; you can get current scene with Scene.buildIndex by doing something like

Yeah, that's what I use to load scenes, but I'm looking for the opposite. Scenemanager has tons of ways to load a scene, but getting the info on the current scene (i.e. we're in scene 5 now, I want to make an int = currentScene; and have that int come out starting at 5 because it's the current scene.

Quote
Code: [Select]
int GetScene()
{
     scene = SceneManager.GetActiveScene();
     return(scene.buildIndex);
}


Maybe this is it?

I don't understand that code though, it returns an int, so say it runs and returns = 5 because we are in scene 5. Where is the variable where that 5 is now stored? Would it be:

Int currentScene = GetScene();

Int Getscene();
{
     scene = SceneManager.GetActiveScene();
     return(scene.buildIndex);
}

?

That doesn't seem right...

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #115 on: April 03, 2022, 02:06:41 PM »
yeah, a method with a return type will spit out what you return as a variable.

you could even do scenemanager.loadscene(GetScene()+1);

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #116 on: April 03, 2022, 02:42:52 PM »
Ok, so I'm working now and that fully decked out timer you posted is giving me a couple of compile errors.

   public int timerValue;
    public Text uiTextElement;
    public Text uiTextElement2;
    public string TypeTextHere = "Enter Text Here";

    float timerCurrent = 0f; // timer value
    bool runTimer = false; // for a simple start / stop toggle
    public Text timerTextUI;

    void StartTimer(float tickrate)
    {
        runTimer = true;
        InvokeRepeating("MyTimer", 0, tickrate);
    }

    void MyTimer()
    {
        if (!runTimer) { StopTimer(); return; }
        timerCurrent++;
        timerTextUI.text = timerCurrent;
    }

    void StopTimer()
    {
        runTimer = false;
        CancelInvoke();
    }

    void RestartMyTimer(float tickrate)
    {
        timerCurrent = 0;
        StartTimer(float, tickrate);
    }


The first bold it doesn't like because it's trying to convert an int (time) to a float (time text).

The second bold it doesn't like because it says you can't have "float" there.

And I'm assuming from this for my game events I'd use:



Also I see you're using tickrate instead of time.deltatime. Is this better for a more stable time between all different computers? I.e. I want big boss to jump out on screen at 5 seconds in on the level because at 5.5 secs something else will fall into the screen covering it and at 4.5 seconds the same thing so only during that 5 second window is the screen open for the boss to jump in.

Void start{startTimer (1.0f)}

Then if currentTime = 5 seconds = boss jump out?


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #117 on: April 03, 2022, 02:52:04 PM »
I fixed the 2nd bold by putting in 1.0f instead of float ticket rate in restart my timer. But code still doesn't like the text thing.

Fixed the first by looking at the previous timer and changing it to "timerTextUI.text = "Time: +" + timerCurrent;"

Will see if it works.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #118 on: April 03, 2022, 02:57:11 PM »
Ok, this works, retiming everything in the stage!

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #119 on: April 03, 2022, 02:59:37 PM »
Actually, is there a way to get the timer to display as a float with a 1.5 secs in the UI display? It's only displaying whole numbers which is a bit of a guessing game in timing this stuff compared to the other timer which was like in the millimillimillisecond on the UI display.