奇怪错误 :a component named *** already exists

苹果菠萝汁 2006-10-29 12:05:09
一直都很正常,突然就遇到了这种错误:
新建窗体后往窗体上放任意一个控件后运行
只要一开这个窗体就会提示a component named *** already exists
往正常的窗体加新控件就没任何问题
请问高手这是怎么回事?根本没法做窗体了
...全文
6760 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ron_xin 2006-10-29
  • 打赏
  • 举报
回复
用记事本打开.dfm,删除该名字的控件名就行了
Fundamentals of the JavaMail API Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Introducing the JavaMail API 3 3. Reviewing related protocols 4 4. Installing JavaMail 6 5. Reviewing the core classes 8 6. Using the JavaMail API 13 7. Searching with SearchTerm 21 8. Exercises 22 9. Wrapup 32 Fundamentals of the JavaMail API Page 1 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 1. Tutorial tips Should I take this tutorial? Looking to incorporate mail facilities into your platform-independent Java solutions? Look no further than the JavaMail API, which offers a protocol-independent model for working with IMAP, POP, SMTP, MIME, and all those other Internet-related messaging protocols. With the help of the JavaBeans Activation Framework (JAF), your applications can now be mail-enabled through the JavaMail API. Concepts After completing this module you will understand the: * Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME * Architecture of the JavaMail framework * Connections between the JavaMail API and the JavaBeans Activation Framework Objectives By the end of this module you will be able to: * Send and read mail using the JavaMail API * Deal with sending and receiving attachments * Work with HTML messages * Use search terms to search for messages Prerequisites Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard Edition (J2SE) 1.2.x or 1.3.x. A general familiarity with object-oriented programming concepts and the Java programming language is necessary. The Java language essentials tutorial can help. copyright 1996-2000 Magelang Institute dba jGuru Contact jGuru has been dedicated to promoting the growth of the Java technology community through evangelism, education, and software since 1995. You can find out more about their activities, including their huge collection of FAQs at jGuru.com . To send feedback to jGuru about this course, send mail to producer@jguru.com . Course author: Formerly with jGuru.com , John Zukowski does strategic Java consulting for JZ Ventures, Inc. His latest book is titled Java Collections from Apress . Fundamentals of the JavaMail API Page 2 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 2. Introducing the JavaMail API What is the JavaMail API? The JavaMail API is an optional package (standard extension) for reading, composing, and sending electronic messages. You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding messages; this is the purview of applications such as sendmail and other Mail Transfer Agent (MTA) type programs. MUA-type programs let users read and write e-mail, whereas MUAs rely on MTAs to handle the actual delivery. The JavaMail API is designed to provide protocol-independent access for sending and receiving messages by dividing the API into two parts: * The first part of the API is the focus of this course --basically, how to send and receive messages independent of the provider/protocol. * The second part speaks the protocol-specific languages, like SMTP, POP, IMAP, and NNTP. With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a sufficient set for free. Fundamentals of the JavaMail API Page 3 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 3. Reviewing related protocols Introduction Before looking into the JavaMail API specifics, let's step back and take a look at the protocols used with the API. There are basically four that you'll come to know and love: * SMTP * POP * IMAP * MIME You will also run across NNTP and some others. Understanding the basics of all the protocols will help you understand how to use the JavaMail API. While the API is designed to be protocol agnostic, you can't overcome the limitations of the underlying protocols. If a capability isn't supported by a chosen protocol, the JavaMail API doesn't magically add the capability on top of it. (As you'll soon see, this can be a problem when working with POP.) SMTP The Simple Mail Transfer Protocol (SMTP) is defined by RFC 821 . It defines the mechanism for delivery of e-mail. In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to the SMTP server of the recipient(s) to eventually be acquired by the user(s) through POP or IMAP. This does not require your SMTP server to be an open relay, as authentication is supported, but it is your responsibility to ensure the SMTP server is configured properly. There is nothing in the JavaMail API for tasks like configuring a server to relay messages or to add and remove e-mail accounts. POP POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. That is all it does, and that is also the source of a lot of confusion. Much of what people are familiar with when using POP, like the ability to see how many new mail messages they have, are not supported by POP at all. These capabilities are built into programs like Eudora or Microsoft Outlook, which remember things like the last mail received and calculate how many are new for you. So, when using the JavaMail API, if you want this type of information, you have to calculate it yourself. IMAP IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060 , IMAP stands for Internet Message Access Protocol, and is currently in version 4, also known as IMAP4. When using IMAP, your mail server must support the protocol. You can't just change your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take Fundamentals of the JavaMail API Page 4 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks advantage of users having multiple folders on the server and these folders can be shared by multiple users. Due to the more advanced capabilities, you might think IMAP would be used by everyone. It isn't. It places a much heavier burden on the mail server, requiring the server to receive the new messages, deliver them to users when requested, and maintain them in multiple folders for each user. While this does centralize backups, as users' long-term mail folders get larger and larger, everyone suffers when disk space is exhausted. With POP, saved messages get offloaded from the mail server. MIME MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822 , RFC 2045 , RFC 2046 , and RFC 2047 . As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and others Because of the split of the JavaMail API between provider and everything else, you can easily add support for additional protocols. Sun maintains a list of third-party providers that take advantage of protocols for which Sun does not provide out-of-the-box support. You'll find support for NNTP (Network News Transport Protocol) [newsgroups], S/MIME (Secure Multipurpose Internet Mail Extensions), and more. Fundamentals of the JavaMail API Page 5 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 4. Installing JavaMail Introduction There are two versions of the JavaMail API commonly used today: 1.2 and 1.1.3. All the examples in this course will work with both. While 1.2 is the latest, 1.1.3 is the version included with the 1.2.1 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is still commonly used. The version of the JavaMail API you want to use affects what you download and install. All will work with JDK 1.1.6+, Java 2 Platform, Standard Edition (J2SE) version 1.2.x, and J2SE version 1.3.x. Note: After installing Sun's JavaMail implementation, you can find many example programs in the demo directory. Installing JavaMail 1.2 To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation, unbundle the javamail-1_2.zip file, and add the mail.jar file to your CLASSPATH. The 1.2 implementation comes with an SMTP, IMAP4, and POP3 provider besides the core classes. After installing JavaMail 1.2, install the JavaBeans Activation Framework. Installing JavaMail 1.1.3 To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation, unbundle the javamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3 implementation comes with an SMTP and IMAP4 provider, besides the core classes. If you want to access a POP server with JavaMail 1.1.3, download and install a POP3 provider. Sun has one available separate from the JavaMail implementation. After downloading and unbundling pop31_1_1.zip, add pop3.jar to your CLASSPATH, too. After installing JavaMail 1.1.3, install the JavaBeans Activation Framework. Installing the JavaBeans Activation Framework All versions of the JavaMail API require the JavaBeans Activation Framework. The framework adds support for typing arbitrary blocks of data and handling it accordingly. This doesn't sound like much, but it is your basic MIME-type support found in many browsers and mail tools today. After downloading the framework, unbundle the jaf1_0_1.zip file, and add the activation.jar file to your CLASSPATH. For JavaMail 1.2 users, you should now have added mail.jar and activation.jar to your CLASSPATH. For JavaMail 1.1.3 users, you should now have added mail.jar, pop3.jar, and activation.jar to your CLASSPATH. If you have no plans of using POP3, you don't Fundamentals of the JavaMail API Page 6 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks need to add pop3.jar to your CLASSPATH. If you don't want to change the CLASSPATH environment variable, copy the jar files to your lib/ext directory under the Java Runtime Environment (JRE) directory. For instance, for the J2SE 1.3 release, the default directory would be C:\jdk1.3\jre\lib\ext on a Windows platform. Using JavaMail with the Java 2 Enterprise Edition If you use J2EE, there is nothing special you have to do to use the basic JavaMail API; it comes with the J2EE classes. Just make sure the j2ee.jar file is in your CLASSPATH and you're all set. For J2EE 1.2.1, the POP3 provider comes separately, so download and follow the steps to include the POP3 provider as shown in the previous section "Installing JavaMail 1.1.3." J2EE 1.3 users get the POP3 provider with J2EE so do not require the separate installation. Neither installation requires you to install the JavaBeans Activation Framework. Exercise Exercise 1. How to set up a JavaMail environment on page 22 Fundamentals of the JavaMail API Page 7 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 5. Reviewing the core classes Introduction Before taking a how-to approach at looking at the JavaMail classes in depth, this section walks you through the core classes that make up the API: Session, Message, Address, Authenticator, Transport, Store, and Folder. All these classes are found in the top-level package for the JavaMail API, javax.mail, though you'll frequently find yourself using subclasses found in the javax.mail.internet package. Session The Session class defines a basic mail session. It is through this session that everything else works. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application. The constructors for the class are private. You can get a single default session that can be shared with the getDefaultInstance() method: Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); Or, you can create a unique session with getInstance(): Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); In both cases, the null argument is an Authenticator object that is not being used at this time. In most cases, it is sufficient to use the shared session, even if working with mail sessions for multiple user mailboxes. You can add the username and password combination in at a later step in the communication process, keeping everything separate. Message Once you have your Session object, it is time to move on to creating the message to send. This is done with a type of Message . Because Message is an abstract class, you must work with a subclass, in most cases javax.mail.internet.MimeMessage .A MimeMessage is an e-mail message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields. To create a Message, pass along the Session object to the MimeMessage constructor: MimeMessage message = new MimeMessage(session); Fundamentals of the JavaMail API Page 8 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Note: There are other constructors, like for creating messages from RFC822-formatted input streams. Once you have your message, you can set its parts, as Message implements the Part interface (with MimeMessage implementing MimePart ). The basic mechanism to set the content is the setContent() method, with arguments for the content and the mime type: message.setContent("Hello", "text/plain"); If, however, you know you are working with a MimeMessage and your message is plain text, you can use its setText() method, which only requires the actual content, defaulting to the MIME type of text/plain: message.setText("Hello"); For plain text messages, the latter form is the preferred mechanism to set the content. For sending other kinds of messages, like HTML messages, use the former. For setting the subject, use the setSubject() method: message.setSubject("First"); Address Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address . Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class. To create an address with just the e-mail address, pass the e-mail address to the constructor: Address address = new InternetAddress("president@whitehouse.gov"); If you want a name to appear next to the e-mail address, you can pass that along to the constructor, too: Address address = new InternetAddress("president@whitehouse.gov", "George Bush"); You will need to create address objects for the message's from field as well as the to field. Unless your mail server prevents you, there is nothing stopping you from sending a message that appears to be from anyone. Once you've created the addresses, you connect them to a message in one of two ways. For identifying the sender, you use the setFrom() and setReplyTo() methods. message.setFrom(address) If your message needs to show multiple from addresses, use the addFrom() method: Fundamentals of the JavaMail API Page 9 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Address address[] = ...; message.addFrom(address); For identifying the message recipients, you use the addRecipient() method. This method requires a Message.RecipientType besides the address. message.addRecipient(type, address) The three predefined types of address are: * Message.RecipientType.TO * Message.RecipientType.CC * Message.RecipientType.BCC So, if the message was to go to the vice president, sending a carbon copy to the first lady, the following would be appropriate: Address toAddress = new InternetAddress("vice.president@whitehouse.gov"); Address ccAddress = new InternetAddress("first.lady@whitehouse.gov"); message.addRecipient(Message.RecipientType.TO, toAddress); message.addRecipient(Message.RecipientType.CC, ccAddress); The JavaMail API provides no mechanism to check for the validity of an e-mail address. While you can program in support to scan for valid characters (as defined by RFC 822) or verify the MX (mail exchange) record yourself, these are all beyond the scope of the JavaMail API. Authenticator Like the java.net classes, the JavaMail API can take advantage of an Authenticator to access protected resources via a username and password. For the JavaMail API, that resource is the mail server. The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the same name. The two don't share the same Authenticator as the JavaMail API works with Java 1.1, which didn't have the java.net variety. To use the Authenticator, you subclass the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. You must register the Authenticator with the session when created. Then, your Authenticator will be notified when authentication is necessary. You could pop up a window or read the username and password from a configuration file (though if not encrypted is not secure), returning them to the caller as a PasswordAuthentication object. Properties props = new Properties(); // fill props with any information Authenticator auth = new MyAuthenticator(); Session session = Session.getDefaultInstance(props, auth); Transport The final part of sending a message is to use the Transport class. This class speaks the Fundamentals of the JavaMail API Page 10 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks protocol-specific language for sending the message (usually SMTP). It's an abstract class and works something like Session. You can use the default version of the class by just calling the static send() method: Transport.send(message); Or, you can get a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); This latter way is best when you need to send multiple messages, as it will keep the connection with the mail server active between messages. The basic send() mechanism makes a separate connection to the server for each method call. Note: To watch the mail commands go by to the mail server, set the debug flag with session.setDebug(true). Store and folder Getting messages starts similarly to sending messages with a Session. However, after getting the session, you connect to a Store , quite possibly with a username and password or Authenticator. Like Transport, you tell the Store what protocol to use: // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); store.connect(host, username, password); After connecting to the Store, you can then get a Folder , which must be opened before you can read messages from it: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); For POP3, the only folder available is the INBOX. If you are using IMAP, you can have other folders available. Note: Sun's providers are meant to be smart. While Message message[] = folder.getMessages(); might look like a slow operation reading every message from the server, only when you actually need to get a part of the message is the message content retrieved. Once you have a Message to read, you can get its content with getContent() or write its content to a stream with writeTo(). The getContent() method only gets the message content, while writeTo() output includes headers. Fundamentals of the JavaMail API Page 11 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks System.out.println(((MimeMessage)message).getContent()); Once you're done reading mail, close the connection to the folder and store. folder.close(aBoolean); store.close(); The boolean passed to the close() method of folder states whether or not to update the folder by removing deleted messages. Moving on Essentially, understanding how to use these seven classes is all you need for nearly everything with the JavaMail API. Most of the other capabilities of the JavaMail API build off these seven classes to do something a little different or in a particular way, like if the content is an attachment. Certain tasks, like searching, are isolated and are discussed later. Fundamentals of the JavaMail API Page 12 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 6. Using the JavaMail API Introduction You've seen how to work with the core parts of the JavaMail API. In the following sections you'll find a how-to approach for connecting the pieces to do specific tasks. Sending messages Sending an e-mail message involves getting a session, creating and filling a message, and sending it. You can specify your SMTP server by setting the mail.smtp.host property for the Properties object passed when getting the Session: String host = ...; String from = ...; String to = ...; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Send message Transport.send(message); You should place the code in a try-catch block, as setting up the message and sending it can throw exceptions. Exercise: Exercise 2. How to send your first message on page 23 Fetching messages For reading mail, you get a session, get and connect to an appropriate store for your mailbox, open the appropriate folder, and get your messages. Also, don't forget to close the connection when done. String host = ...; String username = ...; String password = ...; // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); Fundamentals of the JavaMail API Page 13 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; iexists doesn't mean the flag is supported by all mail servers or providers. For instance, except for deleting messages, the POP protocol supports none of them. Checking for new mail is not a POP task but a task built into mail clients. To find out what flags are supported, ask the folder with getPermanentFlags(). To delete messages, you set the message's DELETED flag: message.setFlag(Flags.Flag.DELETED, true); Open up the folder in READ_WRITE mode first though: folder.open(Folder.READ_WRITE); Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages. folder.close(true); There is an expunge() method of Folder that can be used to delete the messages. However, it doesn't work for Sun's POP3 provider. Other providers may or may not implement the capabilities. It will more than likely be implemented for IMAP providers. Because POP only supports single access to the mailbox, you have to close the folder to delete the messages with Sun's provider. To unset a flag, just pass false to the setFlag() method. To see if a flag is set, check it with isSet(). Authenticating yourself You learned that you can use an Authenticator to prompt for username and password when needed, instead of passing them in as strings. Here you'll actually see how to more fully use authentication. Instead of connecting to the Store with the host, username, and password, you configure the Properties to have the host, and tell the Session about your custom Authenticator instance, as shown here: // Setup properties Properties props = System.getProperties(); props.put("mail.pop3.host", host); // Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getDefaultInstance(props, auth); // Get the store Store store = session.getStore("pop3"); store.connect(); You then subclass Authenticator and return a PasswordAuthentication object from the getPasswordAuthentication() method. The following is one such implementation, with a single field for both. (This isn't a Project Swing tutorial; just enter the two parts in the one field, separated by a comma.) Fundamentals of the JavaMail API Page 15 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks import javax.mail.*; import javax.swing.*; import java.util.*; public class PopupAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username, password; String result = JOptionPane.showInputDialog( "Enter 'username,password'"); StringTokenizer st = new StringTokenizer(result, ","); username = st.nextToken(); password = st.nextToken(); return new PasswordAuthentication(username, password); } } Because the PopupAuthenticator relies on Swing, it will start up the event-handling thread for AWT. This basically requires you to add a call to System.exit() in your code to stop the program. Replying to messages The Message class includes a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, only copying the from or reply-to header to the new recipient. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). MimeMessage reply = (MimeMessage)message.reply(false); reply.setFrom(new InternetAddress("president@whitehouse.gov")); reply.setText("Thanks"); Transport.send(reply); To configure the reply-to address when sending a message, use the setReplyTo() method. Exercise: Exercise 4. How to reply to mail on page 27 Forwarding messages Forwarding messages is a little more involved. There is no single method to call, and you build up the message to forward by working with the parts that make up a message. A mail message can be made up of multiple parts. Each part is a BodyPart , or more specifically, a MimeBodyPart when working with MIME messages. The different body parts get combined into a container called Multipart or, again, more specifically a MimeMultipart . To forward a message, you create one part for the text of your message and a second part with the message to forward, and combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. That's essentially it. To copy the content from one message to another, just copy over its Fundamentals of the JavaMail API Page 16 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks DataHandler , a class from the JavaBeans Activation Framework. // Create the message to forward Message forward = new MimeMessage(session); // Fill in header forward.setSubject("Fwd: " + message.getSubject()); forward.setFrom(new InternetAddress(from)); forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText( "Here you go with the original message:\n\n"); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(message.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); // Send message Transport.send(forward); Working with attachments Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the JavaMail API and get those attachments when you receive the message. Sending attachments: Sending attachments is quite like forwarding messages. You build up the parts to make the complete message. After the first part, your message text, you add other parts where the DataHandler for each is your attachment, instead of the shared handler in the case of a forwarded message. If you are reading the attachment from a file, your attachment data source is a FileDataSource . Reading from a URL, it is a URLDataSource . Once you have your DataSource, just pass it on to the DataHandler constructor, before finally attaching it to the BodyPart with setDataHandler(). Assuming you want to retain the original filename for the attachment, the last thing to do is to set the filename associated with the attachment with the setFileName() method of BodyPart. All this is shown here: // Define message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail Attachment"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("Pardon Ideas"); Fundamentals of the JavaMail API Page 17 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send the message Transport.send(message); When including attachments with your messages, if your program is a servlet, your users must upload the attachment besides telling you where to send the message. Uploading each file can be handled with a form encoding type of multipart/form-data.
Note: Message size is limited by your SMTP server, not the JavaMail API. If you run into problems, consider increasing the Java heap size by setting the ms and mx parameters. Exercise: Exercise 5. How to send attachments on page 28 Getting attachments: Getting attachments out of your messages is a little more involved then sending them because MIME has no simple notion of attachments. The content of your message is a Multipart object when it has attachments. You then need to process each Part, to get the main content and the attachment(s). Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments. However, attachments can also come across with no disposition (and a non-text MIME type) or a disposition of Part.INLINE. When the disposition is either Part.ATTACHMENT or Part.INLINE, you can save off the content for that message part. Just get the original filename with getFileName() and the input stream with getInputStream(). Multipart mp = (Multipart)message.getContent(); for (int i=0, n=multipart.getCount(); iexists, a number is added to the end of the filename until one is found that doesn't exist. // from saveFile() File file = new File(filename); Fundamentals of the JavaMail API Page 18 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks for (int i=0; file.exists(); i++) { file = new File(filename+i); } The code above covers the simplest case where message parts are flagged appropriately. To cover all cases, handle when the disposition is null and get the MIME type of the part to handle accordingly. if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { // Handle plain } else { // Special non-attachment cases here of image/gif, text/html, ... } ... } Processing HTML messages Sending HTML-based messages can be a little more work than sending plain text message, though it doesn't have to be that much more work. It all depends on your specific requirements. Sending HTML messages: If all you need to do is send the equivalent of an HTML file as the message and let the mail reader worry about fetching any embedded images or related pieces, use the setContent() method of Message, passing along the content as a String and setting the content type to text/html. String htmlText = "

Hello

" + ""; message.setContent(htmlText, "text/html")); On the receiving end, if you fetch the message with the JavaMail API, there is nothing built into the API to display the message as HTML. The JavaMail API only sees it as a stream of bytes. To display the message as HTML, you must either use the Swing JEditorPane or some third-party HTML viewer component. if (message.getContentType().equals("text/html")) { String content = (String)message.getContent(); JFrame frame = new JFrame(); JEditorPane text = new JEditorPane("text/html", content); text.setEditable(false); JScrollPane pane = new JScrollPane(text); frame.getContentPane().add(pane); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.show(); } Including images with your messages: On the other hand, if you want your HTML content message to be complete, with embedded images included as part of the message, you must treat the image as an attachment and reference the image with a special cid URL, where the cid is a reference to the Content-ID header of the image attachment. The process of embedding an image is quite similar to attaching a file to a message, the only Fundamentals of the JavaMail API Page 19 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks difference is you have to tell the MimeMultipart that the parts are related by setting its subtype in the constructor (or with setSubType()) and set the Content-ID header for the image to a random string which is used as the src for the image in the img tag. The following demonstrates this completely. String file = ...; // Create the message Message message = new MimeMessage(session); // Fill its headers message.setSubject("Embedded Image"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello

" + ""; messageBodyPart.setContent(htmlText, "text/html"); // Create a related multi-part to combine the parts MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); // Create part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","memememe"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); Exercise: Exercise 6. How to send HTML messages with images on page 29 Fundamentals of the JavaMail API Page 20 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 7. Searching with SearchTerm Introduction The JavaMail API includes a filtering mechanism found in the javax.mail.search package to build up a SearchTerm . Once built, you then ask a Folder what messages match, retrieving an array of Message objects: SearchTerm st = ...; Message[] msgs = folder.search(st); There are 22 different classes available to help you build a search term. * AND terms (class AndTerm) * OR terms (class OrTerm) * NOT terms (class NotTerm) * SENT DATE terms (class SentDateTerm) * CONTENT terms (class BodyTerm) * HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..) Essentially, you build up a logical expression for matching messages, then search. For instance the following term searches for messages with a (partial) subject string of ADV or a from field of friend@public.com. You might consider periodically running this query and automatically deleting any messages returned. SearchTerm st = new OrTerm( new SubjectTerm("ADV:"), new FromStringTerm("friend@public.com")); Message[] msgs = folder.search(st); Fundamentals of the JavaMail API Page 21 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 8. Exercises About the exercises These exercises are designed to provide help according to your needs. For example, you might simply complete the exercise given the information and the task list in the exercise body; you might want a few hints; or you may want a step-by-step guide to successfully complete a particular exercise. You can use as much or as little help as you need per exercise. Moreover, because complete solutions are also provided, you can skip a few exercises and still be able to complete future exercises requiring the skipped ones. Each exercise has a list of any prerequisite exercises, a list of skeleton code for you to start with, links to necessary API pages, and a text description of the exercise goal. In addition, there is help for each task and a solutions page with links to files that comprise a solution to the exercise. Exercise 1. How to set up a JavaMail environment In this exercise you will install Sun's JavaMail reference implementation. After installing, you will be introduced to the demonstration programs that come with the reference implementation. Task 1: Download the latest version of the JavaMail API implementation from Sun. Task 2: Download the latest version of the JavaBeans Activation Framework from Sun. Task 3: Unzip the downloaded packages. You get a ZIP file for all platforms for both packages. Help for task 3: You can use the jar tool to unzip the packages. Task 4: Add the mail.jar file from the JavaMail 1.2 download and the activation.jar file from the JavaBeans Activation Framework download to your CLASSPATH. Help for task 4: Copy the files to your extension library directory. For Microsoft Windows, using the default installation copy, the command might look like the following: cd \javamail-1.2 copy mail.jar \jdk1.3\jre\lib\ext cd \jaf-1.0.1 copy activation.jar \jdk1.3\jre\lib\ext If you don't like copying the files to the extension library directory, detailed instructions are available from Sun for setting your CLASSPATH on Windows NT. Task 5: Go into the demo directory that comes with the JavaMail API implementation and compile the msgsend program to send a test message. Help for task 5: javac msgsend.java Fundamentals of the JavaMail API Page 22 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 6: Execute the program passing in a from address with the -o option, your SMTP server with the -M option, and the to address (with no option). You'll then enter the subject, the text of your message, and the end-of-file character (CTRL-Z) to signal the end of the message input. Help for task 6: Be sure to replace the from address, SMTP server, and to address. java msgsend -o from@address -M SMTP.Server to@address If you are not sure of your SMTP server, contact your system administrator or check with your Internet Service Provider. Task 7: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 1. How to set up a JavaMail environment: Solution Upon successful completion, the JavaMail reference implementation will be in your CLASSPATH. Exercise 2. How to send your first message In the last exercise you sent a mail message using the demonstration program provided with the JavaMail implementation. In this exercise, you'll create the program yourself. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton code: * MailExample.java Task 1: Starting with the skeleton code , get the system Properties. Help for task 1: Properties props = System.getProperties(); Task 2: Add the name of your SMTP server to the properties for the mail.smtp.host key. Fundamentals of the JavaMail API Page 23 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 2: props.put("mail.smtp.host", host); Task 3: Get a Session object based on the Properties. Help for task 3: Session session = Session.getDefaultInstance(props, null); Task 4: Create a MimeMessage from the session. Help for task 4: MimeMessage message = new MimeMessage(session); Task 5: Set the from field of the message. Help for task 5: message.setFrom(new InternetAddress(from)); Task 6: Set the to field of the message. Help for task 6: message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Task 7: Set the subject of the message. Help for task 7: message.setSubject("Hello JavaMail"); Task 8: Set the content of the message. Help for task 8: message.setText("Welcome to JavaMail"); Task 9: Use a Transport to send the message. Help for task 9: Transport.send(message); Task 10: Compile and run the program, passing your SMTP server, from address, and to address on the command line. Fundamentals of the JavaMail API Page 24 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 10: java MailExample SMTP.Server from@address to@address Task 11: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 2. How to send your first message: Solution The following Java source file represents a solution to this exercise: * Solution/MailExample.java Exercise 3. How to check for mail In this exercise, create a program that displays the from address and subject for each message and prompts to display the message content. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton Code * GetMessageExample.java Task 1: Starting with the skeleton code , get or create a Properties object. Help for task 1: Properties props = new Properties(); Task 2: Get a Session object based on the Properties. Help for task 2: Session session = Session.getDefaultInstance(props, null); Task 3: Get a Store for your e-mail protocol, either pop3 or imap. Help for task 3: Store store = session.getStore("pop3"); Task 4: Connect to your mail host's store with the appropriate username and password. Fundamentals of the JavaMail API Page 25 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 4: store.connect(host, username, password); Task 5: Get the folder you want to read. More than likely, this will be the INBOX. Help for task 5: Folder folder = store.getFolder("INBOX"); Task 6: Open the folder read-only. Help for task 6: folder.open(Folder.READ_ONLY); Task 7: Get a directory of the messages in the folder. Save the message list in an array variable named message. Help for task 7: Message message[] = folder.getMessages(); Task 8: For each message, display the from field and the subject. Help for task 8: System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); Task 9: Display the message content when prompted. Help for task 9: System.out.println(message[i].getContent()); Task 10: Close the connection to the folder and store. Help for task 10: folder.close(false); store.close(); Task 11: Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT. Help for task 11: java GetMessageExample POP.Server username password Fundamentals of the JavaMail API Page 26 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Exercise 3. How to check for mail: Solution The following Java source file represents a solution to this exercise. * Solution/GetMessageExample.java Exercise 4. How to reply to mail In this exercise, create a program that creates a canned reply message and attaches the original message if it's plain text. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 3. How to check for mail on page 25 Skeleton Code: * ReplyExample.java Task 1: The skeleton code already includes the code to get the list of messages from the folder and prompt you to create a reply. Task 2: When answered affirmatively, create a new MimeMessage from the original message. Help for task 2: MimeMessage reply = (MimeMessage)message[i].reply(false); Task 3: Set the from field to your e-mail address. Task 4: Create the text for the reply. Include a canned message to start. When the original message is plain text, add each line of the original message, prefix each line with the "> " characters. Help for task 4: To check for plain text messages, check the messages MIME type with mimeMessage.isMimeType("text/plain"). Task 5: Set the message's content, once the message content is fully determined. Task 6: Send the message. Task 7: Compile and run the program, passing your mail server, SMTP server, username, password, and from address on the command line. Answer YES to the messages you want to send replies. Just hit ENTER if you don't. If you want to stop going through your mail before Fundamentals of the JavaMail API Page 27 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks making your way through all the messages, enter QUIT. Help for task 7: java ReplyExample POP.Server SMTP.Server username password from@address Task 8: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 4. How to reply to mail: Solution The following Java source file represents a solution to this exercise. * Solution/ReplyExample.java Exercise 5. How to send attachments In this exercise, create a program that sends a message with an attachment. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 2. How to send your first message on page 23 Skeleton Code: * AttachExample.java Task 1: The skeleton code already includes the code to get the initial mail session. Task 2: From the session, get a Message and set its header fields: to, from, and subject. Task 3: Create a BodyPart for the main message content and fill its content with the text of the message. Help for task 3: BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Task 4: Create a Multipart to combine the main content with the attachment. Add the main content to the multipart. Help for task 4: Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Fundamentals of the JavaMail API Page 28 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 5: Create a second BodyPart for the attachment. Task 6: Get the attachment as a DataSource. Help for task 6: DataSource source = new FileDataSource(filename); Task 7: Set the DataHandler for the message part to the data source. Carry the original filename along. Help for task 7: messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); Task 8: Add the second part of the message to the multipart. Task 9: Set the content of the message to the multipart. Help for task 9: message.setContent(multipart); Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the file as an attachment. Help for task 11: java AttachExample SMTP.Server from@address to@address filename Task 12: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 5. How to send attachments: Solution The following Java source file represents a solution to this exercise. * Solution/AttachExample.java Exercise 6. How to send HTML messages with images In this exercise, create a program that sends an HTML message with an image attachment where the image is displayed within the HTML message. Fundamentals of the JavaMail API Page 29 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 5. How to send attachments on page 28 Skeleton code: * logo.gif * HtmlImageExample.java Task 1: The skeleton code already includes the code to get the initial mail session, create the main message, and fill its headers (to, from, subject). Task 2: Create a BodyPart for the HTML message content. Task 3: Create a text string of the HTML content. Include a reference in the HTML to an image () that is local to the mail message. Help for task 3: Use a cid URL. The content-id will need to be specified for the image later. String htmlText = "

Hello

" + ""; Task 4: Set the content of the message part. Be sure to specify the MIME type is text/html. Help for task 4: messageBodyPart.setContent(htmlText, "text/html"); Task 5: Create a Multipart to combine the main content with the attachment. Be sure to specify that the parts are related. Add the main content to the multipart. Help for task 5: MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); Task 6: Create a second BodyPart for the attachment. Task 7: Get the attachment as a DataSource, and set the DataHandler for the message part to the data source. Task 8: Set the Content-ID header for the part to match the image reference specified in the HTML. Help for task 8: messageBodyPart.setHeader("Content-ID","memememe"); Task 9: Add the second part of the message to the multipart, and set the content of the Fundamentals of the JavaMail API Page 30 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks message to the multipart. Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the images as an inline image within the HTML text. Help for task 11: java HtmlImageExample SMTP.Server from@address to@address filename Task 12: Check if your mail reader recognizes the message as HTML and displays the image within the message, instead of as a link to an external attachment file. Help for task 12: If your mail reader can't display HTML messages, consider sending the message to a friend. Exercise 6. How to send HTML messages with images: Solution The following Java source files represent a solution to this exercise. * Solution/logo.gif * Solution/HtmlImageExample.java Fundamentals of the JavaMail API Page 31 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 9. Wrapup In summary The JavaMail API is a Java package used for reading, composing, and sending e-mail messages and their attachments. It lets you build standards-based e-mail clients that employ various Internet mail protocols, including SMTP, POP, IMAP, and MIME, as well as related protocols such as NNTP, S/MIME, and others. The API divides naturally into two parts. The first focuses on sending, receiving, and managing messages independent of the protocol used, whereas the second focuses on specific use of the protocols. The purpose of this tutorial was to show how to use the first part of the API, without attempting to deal with protocol providers. The core JavaMail API consists of seven classes --Session, Message, Address, Authenticator, Transport, Store, and Folder --all of which are found in javax.mail, the top-level package for the JavaMail API. We used these classes to work through a number of common e-mail-related tasks, including sending messages, retrieving messages, deleting messages, authenticating, replying to messages, forwarding messages, managing attachments, processing HTML-based messages, and searching or filtering mail lists. Finally, we provided a number of step-by-step exercises to help illustrate the concepts presented. Hopefully, this will help you add e-mail functionality to your platform-independent Java applications. Resources You can do much more with the JavaMail API than what's found here. The lessons and exercises found here can be supplemented by the following resources: * Download the JavaMail 1.2 API from the JavaMail API home page . * The JavaBeans Activation Framework is required for versions 1.2 and 1.1.3 of the JavaMail API. * The JavaMail-interest mailing list is a Sun-hosted discussion forum for developers. * Sun's JavaMail FAQ addresses the use of JavaMail in applets and servlets, as well as prototol-specific questions. * Tutorial author John Zukowski maintains jGuru's JavaMail FAQ . * Want to see how others are using JavaMail? Check out Sun's list of third-party products. * If you want more detail about JavaMail, read Rick Grehan's "How JavaMail keeps it simple" (Lotus Developer Network, June 2000). * Benoit Marchal shows how to use Java and XML to produce plain text and HTML newsletters in this two-part series, "Managing e-zines with JavaMail and XSLT" Part 1 (developerWorks, March 2001) and Part 2 (developerWorks, April 2001). * "Linking Applications with E-mail" (Lotus Developer Network, May 2000) discusses how groupware can facilitate communication, collaboration, and coordination among applications. Fundamentals of the JavaMail API Page 32 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Feedback Please let us know whether this tutorial was helpful to you and how we could make it better. We'd also like to hear about other tutorial topics you'd like to see covered. Thanks! For questions about the content of this tutorial, contact the author John Zukowski ( jaz@zukowski.net ) Colophon This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The Toot-O-Matic tool is a short Java program that uses XSLT stylesheets to convert the XML source into a number of HTML pages, a zip file, JPEG heading graphics, and PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. Fundamentals of the JavaMail API Page 33
笔记本的风扇控制 ---------------------------------------- 09 November 2006. Summary of changes for version 20061109: 1) ACPI CA Core Subsystem: Optimized the Load ASL operator in the case where the source operand is an operation region. Simply map the operation region memory, instead of performing a bytewise read. (Region must be of type SystemMemory, see below.) Fixed the Load ASL operator for the case where the source operand is a region field. A buffer object is also allowed as the source operand. BZ 480 Fixed a problem where the Load ASL operator allowed the source operand to be an operation region of any type. It is now restricted to regions of type SystemMemory, as per the ACPI specification. BZ 481 Additional cleanup and optimizations for the new Table Manager code. AcpiEnable will now fail if all of the required ACPI tables are not loaded (FADT, FACS, DSDT). BZ 477 Added #pragma pack(8/4) to acobject.h to ensure that the structures in this header are always compiled as aligned. The ACPI_OPERAND_OBJECT has been manually optimized to be aligned and will not work if it is byte-packed. Example Code and Data Size: These are the sizes for the OS- independent acpica.lib produced by the Microsoft Visual C++ 6.0 32- bit compiler. The debug version of the code includes the debug output trace mechanism and has a much larger code and data size. Previous Release: Non-Debug Version: 78.1K Code, 17.1K Data, 95.2K Total Debug Version: 155.4K Code, 63.1K Data, 218.5K Total Current Release: Non-Debug Version: 77.9K Code, 17.0K Data, 94.9K Total Debug Version: 155.2K Code, 63.1K Data, 218.3K Total 2) iASL Compiler/Disassembler and Tools: Fixed a problem where the presence of the _OSI predefined control method within complex expressions could cause an internal compiler error. AcpiExec: Implemented full region support for multiple address spaces. SpaceId is now part of the REGION object. BZ 429 ---------------------------------------- 11 Oc
Introduction During the software development, I have seen many applications that requires incorporating email support. I remember, once I was to develop an application, which sends emails at the specific time to specific people with the customized messages. For that I developed a COM service that used MAPI. MAPI, i.e. Messaging Application Programming Interface, is the standard messaging architecture and a complete set of functions and object-oriented interfaces. Here I have an Email component, a COM DLL, which is a set of messaging functions that helps you create messaging-enabled applications. This COM component uses Simple MAPI to achieve that. Note: MAPI is used by various industry-standard e-mail clients, such as the Microsoft Exchange client, all versions of Microsoft Outlook and Outlook Express, including QUALCOMM Incorporated (Eudora) and Netscape Communications Corporation. So you can use this component with these client applications also. Component Design The CLSID of the Email component is CLSID_Mail and it has only one interface IMail with the interface ID IID_IMail. CMail is the implementation class and contains following data members: m_MAPILogon Function pointer for MAPILogon m_MAPISendMail Function pointer for MAPISendMail m_MAPISendDocuments Function pointer for MAPISendDocuments m_MAPIFindNext Function pointer for MAPIFindNext m_MAPIReadMail Function pointer for MAPIReadMail m_MAPIResolveName Function pointer for MAPIResolveName m_MAPIAddress Function pointer for MAPIAddress m_MAPILogoff Function pointer for MAPILogoff m_MAPIFreeBuffer Function pointer for MAPIFreeBuffer m_MAPIDetails Function pointer for MAPIDetails m_MAPISaveMail Function pointer for MAPISaveMail IMail have the following functions: IsMapiInstalled Checks if the MAPI is installed on the system. It searches Win.INI file for the MAPI key. If found it returns S_OK. InitMapi After checking the through IsMapiInstalled, it initializes the MAPI function pointers. Method should be called once before using the component. put_strProfileName Takes the name of the outlook profile name you are using to send the email. put_strEmailAddress Sets the recipient email address. You can specify more than one comma (,) separated recipient addresses. put_strRecipient Sets the name you want to specify for the recipients, sets the email names of the sender – it may be different from your specified profile email address. put_strSubject Sets the subject of the email. get_strSubject Returns the email subject. put_strMessage Sets email message text. get_strMessage Returns message text. put_strAttachmentFilePath Sets the email attachment with the full path like “c:\abc.txt”. get_strAttachmentFilePath Returns the path of email attachment. put_strAttachmentFile The display name of the attachment (Sample.txt), by default, it’s the same as that specified in put_strAttachmentFilePath. get_strAttachmentFile Returns the attachment file name. Logon Opens a new logon session if not already opened, using specified outlook profile, name and the profile password, you must logon before sending the email. I have set password to NULL assuming that the profile you will specify have NO password, but you can specify your own password. Automatically called by Send method. Logoff Logs off, and closes the session. Automatically called by Send method after sending the email. Send Sends the email, requires valid outlook profile name, recipient email address and a login session to send email. Steps to execute the demo project The demo project demonstrates the way you can use the component to send an email. In order to execute the demo project, the following settings are required: Step 1: You must have some valid Output Express email account or create one named TestProfile. You can create an email profile in Express from Tools>Accounts menu. This will open Internet Accounts property sheet. On the tab All, click the button Add and then Mail. A wizard will let you create an email account, specify the valid email address. For hotmail account, wizard automatically sets the names of email servers. After successfully creating the account, select the account name from the list in All tab (for hotmail account, the default account name is Hotmail). Open account properties by pressing Properties button and change the account name from default name (say Hotmail) to TestProfile. Step 2: Register the DLL All COM DLLs required to be registered. After copying the DLL source code, you can register the DLL by right clicking the DLL and selecting Register DLL or Register COM component option, or simply by double clicking the DLL. Compiling the DLL code in Visual Studio will automatically register the DLL. Step 3: Logged on to the net Make sure you are logged on to the net. If not, outlook will fail to deliver the email, however, you can still check the composed email in your outbox. How to send email? After specifying the information in the dialog box, click the Send button. A warning message will be displayed, click Send button. Note:The warning dialog is displayed because of the security constraints. If you want to get rid of this dialog box, then you will have to use Extended MAPI instead of simple MAPI. Here is the method CTestEmailDlg::OnSend method, which is used to pass the user specified information to the email object and call the IMail::Send method after setting everything. Collapse | Copy Code //##//##////////////////////////////////////////////////////////////// /////////////////////////////////////////////// // // void CTestEmailDlg::OnSend() // // This module is called when send button is pressed and uses //Email COM DLL to send email - Aisha Ikram // Note: dont forget to initialize COM library using CoInitialize(NULL); //##//##//////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// void CTestEmailDlg::OnSend() { UpdateData(); try{ CComPtr objMail; HRESULT hr; // make sure the DLL is registered hr = objMail.CoCreateInstance(CLSID_Mail); if(SUCCEEDED(hr)) { if(hr== S_OK) { // profile name is compulsory, this is the outlook profile, // i used "outlook express" as configuring it is easier than // "MS outlook" make sure to specify the correct sender's address // for this profile and make sure that outlook express is //the default email client. if(m_strProfile.IsEmpty()) { AfxMessageBox("Please specify email profile name "); return; } if(m_strTo.IsEmpty()) { AfxMessageBox("Please specify recipient's email address "); return; } // by default, it's TestProfile, assumes that a profile with this //name exists in outlook hr= objMail->put_strProfileName((_bstr_t)m_strProfile); hr = objMail->put_strSubject((_bstr_t)m_strSubject); // this is the email or set of email addresses (separated by ,) // which is actually used to send email hr = objMail->put_strEmailAddress((_bstr_t)m_strTo); // recipient is just to show the display name hr = objMail->put_strRecipient((_bstr_t)m_strTo); hr = objMail->put_strAttachmentFilePath((_bstr_t)m_strAttachment); hr = objMail->put_strMessage((_bstr_t)m_strMessage); hr= objMail->Send(); if(hr!=S_OK) AfxMessageBox("Error, make sure the info is correct"); }//if } //if } // try catch(...) { AfxMessageBox("Error, make sure specified info is correct"); } } Check the mail in the recipient inbox. Where to use This component can be extended to incorporate the functionalities like opening an existing inbox to read emails automatically from the inbox and composing new emails etc. It can be used to send emails automatically with customized user messages and attachments to specific people at particular time, especially while using some exe servers or NT services. That's it. If there is any suggestions or comments you are most welcome. Your rating would help me evaluate the standard of my article.
Acknowledgments xiii Introduction xv 1. Making Games the Modular Way 1 1.1 Important Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer Class....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-Destruction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spaceship.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemies..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properties...................................................265 11.10 Weapons and Projectiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scenes......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spaceship..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemies..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, James and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari games in the 1980s. I would like to thank everyone at AK Peters/CRC Press for the help and support and for publishing my work. Finally, a massive thank you goes out to you for buying this book and for wanting to do something as cool as to make games. I sincerely hope this book helps your gamemaking adventures—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I wanted. Sometimes I wanted to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packages came along that could either help me in my quest to make games or even make full games for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of games that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create games within their chosen specific genre. If I wanted to do something outside of the limitations of the software, the source code was inaccessible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different types of games but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I wanted to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In essence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in designing a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genres. Prerequisites You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catches. You may want to consider an upgrade to Unity Pro at some point in the future, to take advantage of some of its advanced features, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making less than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D games that may be sold commercially or otherwise. There are no royalties to pay, either. Unity Pro adds a whole host of professional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free doesn’t pack quite enough power, you may also want to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very important point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the examples as simple as possible! This book is about making games, not about learning to program. What This Book Doesn’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniques and concepts offered in this book are meant to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experiences in game development, you make your own rules and draw your own conclusions. Additional material is available from the CRC Press Web site: http://www.crcpress. com/product/isbn/9781466581401. 1 1 Making Games the Modular Way When I first started making games, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a professional developer, landing a job at a game development studio making browser-based games, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great games (both visually and gameplay-wise) very quickly. One secret to his success lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the essentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, resulting in games that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my eyes. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was substantially reduced, which left more time to concentrate on making better games. This book is based on a similar concept of a game-centric framework for use with many different types of games, rather than a set of different games in different styles. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduces recoding, repurposing, or adaptation time. 2 1. Making Games the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different games that use the same framework to make new games, and we can share several of the same core scripts in many different games. The framework takes care of the essentials, and we add a little “glue” code to pull everything together the way we want it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own games, the framework may serve either as a base to build your games on or simply as a tutorial test bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the design decisions of the framework. 1.1 Important Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselves but more because I had solved the problems in a different way that meant I had no real requirement to learn anything new. For most programmers, these concepts will be second nature and perhaps something taught in school, but I did not know how important they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relevant player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finishes. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it makes it easier to migrate them from project to project. Essentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that features a completely different type of gameplay— for example, alien characters running around a track instead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can access it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Important Programming Concepts important to me to design scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and responding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just doesn’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It doesn’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it doesn’t really matter just as long as when you want them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to access), whereas others may be better attached to other scripts. We deal with these on a case-by-case basis. To get things started, we will be looking at some of the ways that these manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistencies in the application of the term in one case versus another. I’ll try my best to keep things logical, but that doesn’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An important part of our manager- and component-based structures is how our scripts are going to communicate with each other. It is inevitable that we will need to access our scripts from a multitude of other areas of the game, which means we should try to provide interfaces that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variables set in the editor by the Inspector window. The easiest way to have your scripts talk to each other is to have direct references to them in the form of public variables within a class. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we want to talk to. Within the class, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Games the Modular Way 2. GameObject referencing using SendMessage. SendMessage is a great way to send a message to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return result. For example, SomeGameObject.SendMessage("DoSomething"); SendMessage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendMessage call. (SendMessageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendMessage("AddScore",2); SomeGameObject.SendMessage("AddScore", SendMessageOptions.RequireReceiver); SomeGameObject.SendMessage("AddScore", SendMessageOptions.DontRequireReceiver); 3. Static variables. The static variable type is useful in that it extends across the entire system; it will be accessible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may want to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variables extend across the entire program, you can have private and public static variables. Things get a little tricky when you try to understand the differences between public and private static types—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be accessed from other classes and other types of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stores a reference to itself in a public static variable like this: gateway = this; 3. In any other class, we can now access the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Important Programming Concepts Private static A private static variable exists within the class it was declared and in any other instances of the same class. Other classes/types of script will not be able to access it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single instance of the player class, to be ready to use for all the other instances of the same class. All player.cs scripts will be able to access the same instance of the PlayerManager. 4. The singleton design pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The biggest danger with this method is that it is possible to create multiple instances of the same script. If this happens, you may find that your player code is talking to the wrong instance of the game controller. A singletonis a commonly used design pattern that allows for only one instance of a particular class to be instantiated at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variables” method earlier in this section, but in implementing a singleton class, we will be adding some extra code to make sure that only one instance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variables can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be accessed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public static function. Other scripts access the public function to gain access to the private static instance of this script, which is returned via the public function so that only one instance of the object will ever exist in a scene regardless of how many components it is attached to and regardless of how many times it is instantiated. A simple singleton structure: public class MySingleton { private static MySingleton instance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Games the Modular Way { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton."); return; } instance = this; } public static MySingleton Instance { get { if (instance == null) { new MySingleton (); } return instance; } } } The singleton instance of our script may be accessed anywhere, by any script, simply with the following syntax: MySingleton.Instance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to describe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The types of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to describe how our car behaves, we may also describe the engine and wheels. These relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car class Wheels function Engine function 7 1.1 Important Programming Concepts

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧